我正在尝试同时更改多个数据框中的国家/地区名称,但每个数据框都有不同的列长度。例如:
df1 <- data.frame(country = c('Austria','UK'), year = c(2015,2012), data = c(10,12))
df2 <- data.frame(country = c('Austria','UK'), year = c(2015,2012), prop = c(0.5,0.2), gender = c('male','female'))
df3 <- data.frame(country = c('Austria','UK'), year = c(2015,2012))
我需要改变英国&#34;到#34;英国&#34;在所有数据框中。我正在做以下事情:
aList <- list(df1,df2,df3)
lapply(aList, function(df){
df$new_country <- df%>% mutate (new_country = ifelse(df$country == 'UK', 'United Kingdom', df$country))
})
但我没有得到改变。我在控制台中看到了这一点:
[[1]]
country year data new_country
1 Austria 2015 10 1
2 UK 2012 12 United Kingdom
[[2]]
country year prop gender new_country
1 Austria 2015 0.5 male 1
2 UK 2012 0.2 female United Kingdom
[[3]]
country year new_country
1 Austria 2015 1
2 UK 2012 United Kingdom
但是当我打开列表时,我看不到列表中的值,奥地利的值是1,它应该是奥地利。有人可以帮忙吗?
答案 0 :(得分:0)
data.table解决方案:
library(data.table)
df1 <- data.table(country = c('Austria','UK'), year = c(2015,2012), data = c(10,12))
df2 <- data.table(country = c('Austria','UK'), year = c(2015,2012), prop = c(0.5,0.2), gender = c('male','female'))
df3 <- data.table(country = c('Austria','UK'), year = c(2015,2012))
aList <- list(df1,df2,df3)
bList <- lapply(aList, function(x) x[,lapply(.SD, function(x) gsub("UK", "United Kingdom", x))])