我有7个数据帧,其中第一个变量只是50个状态的列表。问题在于,在其中一些州,州都是首都,都是小写或混合。而不是编写7个不同的tolower()命令,我想知道是否有办法使用循环或lapply()?
我尝试过这两种方式,但都没有效果:
ivs <- c("taxes","urban","gini","educ","inc","cong"))## a character vector of the data frame names
for (i in length(1:ivs)){
i$state <- tolower(i$state)
}
这样:
ivs <- c("taxes","urban","gini","educ","inc","cong"))
sapply(ivs, function(x) {
x$state <- tolower(x$state)
})
感谢您的帮助!
答案 0 :(得分:0)
如果你想使用for循环
,试试这个ivs <- list(taxes,urban,gini,educ,inc,cong))## Put your dataframes into a list
for (i in ivs){
i$state <- tolower(i$state)
}
答案 1 :(得分:0)
您可以将apply
放在lapply
示例:
l <-
list(
data.frame(state = c("ARIZONA", "teXaS")),
data.frame(state = c("arizona", "TEXAS")),
data.frame(state = c("AriZonA", "TEXaS"))
)
lapply(l, function(x) apply(x[1], 2, tolower))
#[[1]]
# state
#[1,] "arizona"
#[2,] "texas"
#
#[[2]]
# state
#[1,] "arizona"
#[2,] "texas"
#
#[[3]]
# state
#[1,] "arizona"
#[2,] "texas"
答案 2 :(得分:0)
您可以尝试以下方式:
for( v in ivs){
eval(parse(text=paste0(v,"$state <- tolower(",v,"$state)")))
}
答案 3 :(得分:0)
lapply(dflist, function(df) {
df[[1]] <- tolower(df[[1]])
df
})