简体   繁体   中英

R setting a value based on another column by group

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 eg 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.

After grouping by 'country', mutate to get the corresponding 'tfp.level' for 'year' value 1980

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 

Or using base R

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

data

df1 <- structure(list(country = c("Australia", "Australia", "Australia", 
"Australia", "Australia", "Australia", "Costa Rica", "Costa Rica", 
"Costa Rica", "Costa Rica"), ISO = c("AUS", "AUS", "AUS", "AUS", 
"AUS", "AUS", "CRI", "CRI", "CRI", "CRI"), year = c(1980L, 1981L, 
1982L, 1983L, 1984L, 1985L, 1980L, 1981L, 1982L, 1983L), 
`tfp level` = c(0.796980202, 
0.808527768, 0.790943801, 0.818122745, 0.827925146, 0.825170755, 
1.082085967, 1.033975005, 0.934024811, 0.920588791)),
class = "data.frame", row.names = c(NA, 
-10L))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM