R setting a value based on another column by group

时间:2019-01-07 13:42:45

标签: r dplyr

I have a data frame in R that looks like the one below. I want to create a new column called tfp level[1980] that takes the 1980 value of tfp level. Taking into account a grouping by country.

So e.g. Australia will take the value 0.796980202 for each year and Costa Rica 1.082085967 for each year.

country     ISO year    tfp level    tfp level[1980]
Australia   AUS 1980    0.796980202 
Australia   AUS 1981    0.808527768 
Australia   AUS 1982    0.790943801 
Australia   AUS 1983    0.818122745 
Australia   AUS 1984    0.827925146     
Australia   AUS 1985    0.825170755 
Costa Rica  CRI 1980    1.082085967 
Costa Rica  CRI 1981    1.033975005 
Costa Rica  CRI 1982    0.934024811 
Costa Rica  CRI 1983    0.920588791

There must be a way to solve this neatly with dplyr, for instance using the group_by command, but I can't get to a good solution myself.

Thanks.

1 个答案:

答案 0 :(得分:2)

按“国家”分组后,mynum获得“ 1980”年值的相应“ tfp.level”

mutate

或使用library(dplyr) df1 %>% group_by(country) %>% mutate(tfllevel1980 = `tfp level`[year == 1980]) # A tibble: 10 x 5 # Groups: country [2] # country ISO year `tfp level` tfllevel1980 # <chr> <chr> <int> <dbl> <dbl> # 1 Australia AUS 1980 0.797 0.797 # 2 Australia AUS 1981 0.809 0.797 # 3 Australia AUS 1982 0.791 0.797 # 4 Australia AUS 1983 0.818 0.797 # 5 Australia AUS 1984 0.828 0.797 # 6 Australia AUS 1985 0.825 0.797 # 7 Costa Rica CRI 1980 1.08 1.08 # 8 Costa Rica CRI 1981 1.03 1.08 # 9 Costa Rica CRI 1982 0.934 1.08 #10 Costa Rica CRI 1983 0.921 1.08

base R

数据

df1$tfplevel1980 <- with(df1, ave(`tfp level` * (year == 1980), 
                 country, FUN = function(x) x[x!= 0]))