Is it possible to construct a function, say my_mut(df, condition) such that df is a dataframe, condition is a string describing a mutation, and somewhere in the function, the mutation of df according to condition is used?
For example, if df has a foo column and you run my_mut(df, "foo = 2*foo"), then somewhere within my_mut() there would be a row that produces the same dataframe as df %>% mutate(foo = 2*foo).
I managed to do something similar with filter using eval and parse.
update_filt <- function(df,
filt,
col){
sub <- df %>%
filter(eval(parse(text = filt))) %>%
mutate("{{col}}" := 2*{{ col }})
remain <- df %>%
filter(eval(parse(
text = paste0("!(",filt,")")
))
)
return(rbind(sub, remain))
}
I am not sure the update_filt function is faultproof, but it works in some cases at least, e.g., library(gapminder) date_filt(gapminder, "year == 1952", pop) returns the expected outcome.
The same trick does not seem to work with mutate though. For example,
update_mut <- function(df, mutation){
# Evaluate mutation expression
df %>% mutate(eval(parse(text = mutation))
}
produces outcomes like
library(gapminder)
update_mut(gapminder, "year = 2*year")
# A tibble: 1,704 × 7
country continent year lifeExp pop gdpPercap `eval(parse(text = mutation))`
<fct> <fct> <int> <dbl> <int> <dbl> <dbl>
1 Afghanistan Asia 1952 28.8 8425333 779. 3904
2 Afghanistan Asia 1957 30.3 9240934 821. 3914
3 Afghanistan Asia 1962 32.0 10267083 853. 3924
4 Afghanistan Asia 1967 34.0 11537966 836. 3934
5 Afghanistan Asia 1972 36.1 13079460 740. 3944
6 Afghanistan Asia 1977 38.4 14880372 786. 3954
7 Afghanistan Asia 1982 39.9 12881816 978. 3964
8 Afghanistan Asia 1987 40.8 13867957 852. 3974
9 Afghanistan Asia 1992 41.7 16317921 649. 3984
10 Afghanistan Asia 1997 41.8 22227415 635. 3994
# … with 1,694 more rows
Instead of the expected
gapminder %>% mutate(year = 2*year)
# A tibble: 1,704 × 6
country continent year lifeExp pop gdpPercap
<fct> <fct> <dbl> <dbl> <int> <dbl>
1 Afghanistan Asia 3904 28.8 8425333 779.
2 Afghanistan Asia 3914 30.3 9240934 821.
3 Afghanistan Asia 3924 32.0 10267083 853.
4 Afghanistan Asia 3934 34.0 11537966 836.
5 Afghanistan Asia 3944 36.1 13079460 740.
6 Afghanistan Asia 3954 38.4 14880372 786.
7 Afghanistan Asia 3964 39.9 12881816 978.
8 Afghanistan Asia 3974 40.8 13867957 852.
9 Afghanistan Asia 3984 41.7 16317921 649.
10 Afghanistan Asia 3994 41.8 22227415 635.
# … with 1,694 more rows
library(dplyr, warn.conflicts = FALSE)
my_mut <- function(df, df_filter, ...){
df %>%
filter({{ df_filter }}) %>%
mutate(newvar = 'other function stuff',
...)
}
example_df <- data.frame(a = c('zebra', 'some value'),
b = 1:2)
example_df %>%
my_mut(df_filter = a == 'some value',
b = b*5)
#> a b newvar
#> 1 some value 10 other function stuff
Created on 2021-11-11 by the reprex package (v2.0.1)
If you can't use ... because you're already using it in the function for something else, you could wrap the mutation argument in tibble when calling the function.
library(dplyr, warn.conflicts = FALSE)
my_mut <- function(df, df_filter, mutation){
df %>%
filter({{ df_filter }}) %>%
mutate(newvar = 'other function stuff',
{{ mutation }})
}
example_df <- data.frame(a = c('zebra', 'some value'),
b = 1:2)
example_df %>%
my_mut(df_filter = a == 'some value',
mutation = tibble(b = b*5))
#> a b newvar
#> 1 some value 10 other function stuff
Created on 2021-11-11 by the reprex package (v2.0.1)
If your formula is always like origianl = do_something_original(), this may helps.(for dplyr version >= 1.0)
library(dplyr)
library(stringr)
update_mut <- function(df, mutation){
xx <- word(mutation, 1)
df %>%
mutate("{xx}" := eval(parse(text = mutation)))
}
update_mut(gapminder, "year = 2*year")
country continent year lifeExp pop gdpPercap
<fct> <fct> <dbl> <dbl> <int> <dbl>
1 Afghanistan Asia 3904 28.8 8425333 779.
2 Afghanistan Asia 3914 30.3 9240934 821.
3 Afghanistan Asia 3924 32.0 10267083 853.
4 Afghanistan Asia 3934 34.0 11537966 836.
5 Afghanistan Asia 3944 36.1 13079460 740.
6 Afghanistan Asia 3954 38.4 14880372 786.
7 Afghanistan Asia 3964 39.9 12881816 978.
8 Afghanistan Asia 3974 40.8 13867957 852.
9 Afghanistan Asia 3984 41.7 16317921 649.
10 Afghanistan Asia 3994 41.8 22227415 635.
The problem is that mutate doesn't understand the assignment, because all the syntax is evaluated inside eval. So mutate simply thinks this is a nameless expression and assigns as its name the whole text of the expression.
One way to circumvent this would be to eval the whole thing, including the mutate verb, as below.
update_mut <- function(df, mutation) {
# Evaluate the mutation expression
eval(parse(text = paste0("mutate(df, ", mutation, ")")))
}
Another way would be, inside the update_mut function, to split the mutation parameter by the = character, therefore obtaining the name of the variable and the expressions. Therefore you could use a dynamic variable assingment in mutate. However this would only be more to do, since the above code simply solves the problem.
Related
According to the answer of lhs,
https://stackoverflow.com/a/72467827/11124121
#From lhs
library(tidyverse)
data("population")
# create some data to interpolate
population_5 <- population %>%
filter(year %% 5 == 0) %>%
mutate(female_pop = population / 2,
male_pop = population / 2)
interpolate_func <- function(variable, data) {
data %>%
group_by(country) %>%
# can't interpolate if only one year
filter(n() >= 2) %>%
group_modify(~as_tibble(approx(.x$year, .x[[variable]],
xout = min(.x$year):max(.x$year)))) %>%
set_names(c("country", "year", paste0(variable, "_interpolated"))) %>%
ungroup()
}
The data that already exists, i.e. year 2000 and 2005 are also interpolated. I want to keep the orginal data and only interpolate the missing parts, that is,
2001-2004 ; 2006-2009
Therefore, I would like to construct a list:
population_5_list = list(population_5 %>% filter(year %in% c(2000,2005)),population_5 %>% filter(year %in% c(2005,2010)))
And impute the dataframes in the list one by one.
However, a error appeared:
Error in UseMethod("group_by") :
no applicable method for 'group_by' applied to an object of class "list"
I am wondering how can I change the interpolate_func into purrr format, in order to apply to list.
We need to loop over the list with map
library(purrr)
library(dplyr)
map(population_5_list,
~ map(vars_to_interpolate, interpolate_func, data = .x) %>%
reduce(full_join, by = c("country", "year")))
-output
[[1]]
# A tibble: 1,266 × 5
country year population_interpolated female_pop_interpolated male_pop_interpolated
<chr> <int> <dbl> <dbl> <dbl>
1 Afghanistan 2000 20595360 10297680 10297680
2 Afghanistan 2001 21448459 10724230. 10724230.
3 Afghanistan 2002 22301558 11150779 11150779
4 Afghanistan 2003 23154657 11577328. 11577328.
5 Afghanistan 2004 24007756 12003878 12003878
6 Afghanistan 2005 24860855 12430428. 12430428.
7 Albania 2000 3304948 1652474 1652474
8 Albania 2001 3283184. 1641592. 1641592.
9 Albania 2002 3261421. 1630710. 1630710.
10 Albania 2003 3239657. 1619829. 1619829.
# … with 1,256 more rows
# ℹ Use `print(n = ...)` to see more rows
[[2]]
# A tibble: 1,278 × 5
country year population_interpolated female_pop_interpolated male_pop_interpolated
<chr> <int> <dbl> <dbl> <dbl>
1 Afghanistan 2005 24860855 12430428. 12430428.
2 Afghanistan 2006 25568246. 12784123. 12784123.
3 Afghanistan 2007 26275638. 13137819. 13137819.
4 Afghanistan 2008 26983029. 13491515. 13491515.
5 Afghanistan 2009 27690421. 13845210. 13845210.
6 Afghanistan 2010 28397812 14198906 14198906
7 Albania 2005 3196130 1598065 1598065
8 Albania 2006 3186933. 1593466. 1593466.
9 Albania 2007 3177735. 1588868. 1588868.
10 Albania 2008 3168538. 1584269. 1584269.
# … with 1,268 more rows
I want to calculate the change in life expectancy over the years for each country in the gapminder dataset. I am using the lag function to calculate this difference for each country with the data set.
i.e:
v <- 1:10
print(v)
v-v
v-lag(v)
When I try implementing this to the gapminder dataset, I end up calculating the difference in life expectancy between two different countries, which is not what I want to find. The code calculates the difference between the life expectancy of country B's earliest year and country A's earliest year in error.
my code:
library(gapminder)
library(tidyverse)
library(tidyr)
library(readr)
library(dplyr)
gm <- gapminder
explife <- gm %>%
group_by(country) %>%
mutate(inc = lifeExp - lag(lifeExp)) %>%
arrange(desc(inc)) %>%
select(country, year, lifeExp, inc)
print(explife)
I also tried grouping by year as well, but all the values are NA.
library(gapminder)
library(tidyverse)
library(tidyr)
library(readr)
library(dplyr)
gm <- gapminder
explife <- gm %>%
group_by(country, year) %>%
mutate(inc = lifeExp - lag(lifeExp)) %>%
arrange(desc(inc)) %>%
select(country, year, lifeExp, inc)
print(explife)
The key lines of your code do seem to give the expected results, with all countries receiving NAs in their earliest years:
library(dplyr)
gapminder::gapminder |>
group_by(country) |>
mutate(inc = lifeExp - lag(lifeExp)) |>
filter(is.na(inc))
#> # A tibble: 142 × 7
#> # Groups: country [142]
#> country continent year lifeExp pop gdpPercap inc
#> <fct> <fct> <int> <dbl> <int> <dbl> <dbl>
#> 1 Afghanistan Asia 1952 28.8 8425333 779. NA
#> 2 Albania Europe 1952 55.2 1282697 1601. NA
#> 3 Algeria Africa 1952 43.1 9279525 2449. NA
#> 4 Angola Africa 1952 30.0 4232095 3521. NA
#> 5 Argentina Americas 1952 62.5 17876956 5911. NA
#> 6 Australia Oceania 1952 69.1 8691212 10040. NA
#> 7 Austria Europe 1952 66.8 6927772 6137. NA
#> 8 Bahrain Asia 1952 50.9 120447 9867. NA
#> 9 Bangladesh Asia 1952 37.5 46886859 684. NA
#> 10 Belgium Europe 1952 68 8730405 8343. NA
#> # … with 132 more rows
I'm trying to create a new variable in R containing the initial values of another variable (crime) based on groups (countries) considering the initial period of time observable per group (on panel data framework), my current data looks like this:
country
year
Crime
Albania
2016
2.7369478
Albania
2017
2.0109779
Argentina
2002
9.474084
Argentina
2003
7.7898825
Argentina
2004
6.0739941
And I want it to look like this:
country
year
Crime
Initial_Crime
Albania
2016
2.7369478
2.7369478
Albania
2017
2.0109779
2.7369478
Argentina
2002
9.474084
9.474084
Argentina
2003
7.7898825
9.474084
Argentina
2004
6.0739941
9.474084
I saw that ddply could make it work this way, but the problem is that it is not longer supported by the latest R updates.
Thank you in advance.
Maybe arrange by year, then after grouping by country set Initial_Crime to be the first Crime in the group.
library(tidyverse)
df %>%
arrange(year) %>%
group_by(country) %>%
mutate(Initial_Crime = first(Crime))
Output
country year Crime Initial_Crime
<chr> <int> <dbl> <dbl>
1 Argentina 2002 9.47 9.47
2 Argentina 2003 7.79 9.47
3 Argentina 2004 6.07 9.47
4 Albania 2016 2.74 2.74
5 Albania 2017 2.01 2.74
library(data.table)
setDT(data)[, Initial_Crime:=.SD[1,Crime], by=country]
country year Crime Initial_Crime
1: Albania 2016 2.736948 2.736948
2: Albania 2017 2.010978 2.736948
3: Argentina 2002 9.474084 9.474084
4: Argentina 2003 7.789883 9.474084
5: Argentina 2004 6.073994 9.474084
A data.table solution
setDT(df)
df[, x := 1:.N, country
][x==1, initial_crime := crime
][, initial_crime := nafill(initial_crime, type = "locf")
][, x := NULL
]
I have a data set where I am looking at longitudinal data for countries.
master.set <- data.frame(
Country = c(rep("Afghanistan", 3), rep("Albania", 3)),
Country.ID = c(rep("Afghanistan", 3), rep("Albania", 3)),
Year = c(2015, 2016, 2017, 2015, 2016, 2017),
Happiness.Score = c(3.575, 3.360, 3.794, 4.959, 4.655, 4.644),
GDP.PPP = c(1766.593, 1757.023, 1758.466, 10971.044, 11356.717, 11803.282),
GINI = NA,
Status = 2,
stringsAsFactors = F
)
> head(master.set)
Country Country.ID Year Happiness.Score GDP.PPP GINI Status
1 Afghanistan Afghanistan 2015 3.575 1766.593 NA 2
2 Afghanistan Afghanistan 2016 3.360 1757.023 NA 2
3 Afghanistan Afghanistan 2017 3.794 1758.466 NA 2
4 Albania Albania 2015 4.959 10971.044 NA 2
5 Albania Albania 2016 4.655 11356.717 NA 2
6 Albania Albania 2017 4.644 11803.282 NA 2
I created that Country.ID variable with the intent of turning them into numerical values 1:159.
I am hoping to avoid doing something like this to replace the value at each individual observation:
master.set$Country.ID <- master.set$Country.ID[master.set$Country.ID == "Afghanistan"] <- 1
As I implied, there are 159 countries listed in the data set. Because it' longitudinal, there are 460 observations.
Is there any way to use a for loop to save me a lot of time? Here is what I attempted. I made a couple of lists and attempted to use an ifelse command to tell R to label each country the next number.
Here is what I have:
#List of country names
N.Countries <- length(unique(master.set$Country))
Country <- unique(master.set$Country)
Country.ID <- unique(master.set$Country.ID)
CountryList <- unique(master.set$Country)
#For Loop to make Country ID numerically match Country
for (i in 1:460){
for (j in N.Countries){
master.set[[Country.ID[i]]] <- ifelse(master.set[[Country[i]]] == CountryList[j], j, master.set$Country)
}
}
I received this error:
Error in `[[<-.data.frame`(`*tmp*`, Country.ID[i], value = logical(0)) :
replacement has 0 rows, data has 460
Does anyone know how I can accomplish this task? Or will I be stuck using the ifelse command 159 times?
Thanks!
Maybe something like
master.set$Country.ID <- as.numeric(as.factor(master.set$Country.ID))
Or alternatively, using dplyr
library(tidyverse)
master.set <- master.set %>% mutate(Country.ID = as.numeric(as.factor(Country.ID)))
Or this, which creates a new variable Country.ID2based on a key-value pair between Country.ID and a 1:length(unique(Country)).
library(tidyverse)
master.set <- left_join(master.set,
data.frame( Country = unique(master.set$Country),
Country.ID2 = 1:length(unique(master.set$Country))))
master.set
#> Country Country.ID Year Happiness.Score GDP.PPP GINI Status
#> 1 Afghanistan Afghanistan 2015 3.575 1766.593 NA 2
#> 2 Afghanistan Afghanistan 2016 3.360 1757.023 NA 2
#> 3 Afghanistan Afghanistan 2017 3.794 1758.466 NA 2
#> 4 Albania Albania 2015 4.959 10971.044 NA 2
#> 5 Albania Albania 2016 4.655 11356.717 NA 2
#> 6 Albania Albania 2017 4.644 11803.282 NA 2
#> Country.ID2
#> 1 1
#> 2 1
#> 3 1
#> 4 2
#> 5 2
#> 6 2
library(dplyr)
df<-data.frame("Country"=c("Afghanistan","Afghanistan","Afghanistan","Albania","Albania","Albania"),
"Year"=c(2015,2016,2017,2015,2016,2017),
"Happiness.Score"=c(3.575,3.360,3.794,4.959,4.655,4.644),
"GDP.PPP"=c(1766.593,1757.023,1758.466,10971.044,11356.717,11803.282),
"GINI"=NA,
"Status"=rep(2,6))
df1<-df %>% arrange(Country) %>% mutate(Country_id = group_indices_(., .dots="Country"))
View(df1)
So, I currently have a dataframe that looks like:
country continent year lifeExp pop gdpPercap
<fctr> <fctr> <int> <dbl> <int> <dbl>
1 Afghanistan Asia 1952 28.801 8425333 779.4453
2 Afghanistan Asia 1957 30.332 9240934 820.8530
3 Afghanistan Asia 1962 31.997 10267083 853.1007
4 Afghanistan Asia 1967 34.020 11537966 836.1971
5 Afghanistan Asia 1972 36.088 13079460 739.9811
6 Afghanistan Asia 1977 38.438 14880372 786.1134
There are 140+ countries. The years are in 5 year intervals. From 1952- 2007 I want to reshape my dataframe such that I get.
Country gdpPercap(1952) gdpPercap(1957) ... gdpPercap(2007)
<fctr> <dbl>
1 Afghanistan 974.5803 .... ...
2 Albania 5937.0295 ... ...
3 Algeria 6223.3675 ... ...
4 Angola 4797.2313
5 Argentina 12779.3796
6 Australia 34435.3674
7 Austria 36126.4927
8 Bahrain 29796.0483
9 Bangladesh 1391.2538
10 Belgium 33692.6051
My attempt is this:
gapminder %>% #my dataframe
filter(year >= 1952) %>%
group_by(country) %>%
summarise(gdpPercap = mean(gdpPercap))
OUTPUT:
country gdpPercap <- but this takes the mean of gdpPercap from 1952-2007
<fctr> <dbl>
1 Afghanistan 802.6746
2 Albania 3255.3666
3 Algeria 4426.0260
4 Angola 3607.1005
5 Argentina 8955.5538
6 Australia 19980.5956
7 Austria 20411.9163
8 Bahrain 18077.6639
9 Bangladesh 817.5588
10 Belgium 19900.7581
# ... with 132 more rows
Any ideas? PS: I'm new to R. I'm also looking at melt(). Any help will be appreciated!
tidyr::spread() would solve your problem
library(dplyr); library(tidyr)
gapminder %>%
select(country, year, gdpPercap) %>%
spread(year, gdpPercap)
You should use year also in group_by, and after summary, just reshape the data the way you want using dcast or rehape
Here is a sample solution :
library(dplyr)
library(reshape2)
gapminder <- data.frame(cbind(gdpPercap=runif(10000), year =as.integer(seq(from=1952, to=2007, by=5)), country = c("India", "US", "UK")))
gapminder$gdpPercap <- as.numeric(as.character(gapminder$gdpPercap))
gapminder$year <- as.integer(as.character(gapminder$year))
gapminder %>% #my dataframe
filter(year >= 1952) %>%
group_by(country, year) %>%
summarise(gdpPercap = mean(gdpPercap)) %>%
dcast(country ~ year, value.var="gdpPercap")
I have to generate a new data, because your example is not reproducible. Go through the link How to make a great R reproducible example?. It helps in answering and understanding the problem, as well as, quicker answers.
Built-in reshape can do this.
foo.data.frame <- data.frame(
Country=rep(c("Here", "There"), each=3),
year=rep(c(1952, 1957, 1962),2),
gdpPercap=779:784
# ... other variables
)
reshape(foo.data.frame[, c("Country", "year", "gdpPercap")],
timevar="year", idvar="Country", direction="wide", sep=" ")
# Country gdpPercap 1952 gdpPercap 1957 gdpPercap 1962
# 1 Here 779 780 781
# 4 There 782 783 784