更改 R 中数据帧列表中的变量
Changing a variable in a list of dataframes in R
我有 7 个数据框,其中第一个变量只是 50 个州的列表。问题是在其中一些州中,州都是大写字母,全部是小写字母或混合字母。我想知道是否有办法使用循环或 lapply()?
来执行此操作,而不是编写 7 个不同的 tolower() 命令
我试过这两种方法都没有用:
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)
})
感谢您的帮助!
如果你想使用 for 循环,试试这个
ivs <- list(taxes,urban,gini,educ,inc,cong))## Put your dataframes into a list
for (i in ivs){
i$state <- tolower(i$state)
}
您可以将 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"
您可以尝试类似的方法:
for( v in ivs){
eval(parse(text=paste0(v,"$state <- tolower(",v,"$state)")))
}
lapply(dflist, function(df) {
df[[1]] <- tolower(df[[1]])
df
})
我有 7 个数据框,其中第一个变量只是 50 个州的列表。问题是在其中一些州中,州都是大写字母,全部是小写字母或混合字母。我想知道是否有办法使用循环或 lapply()?
来执行此操作,而不是编写 7 个不同的 tolower() 命令我试过这两种方法都没有用:
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)
})
感谢您的帮助!
如果你想使用 for 循环,试试这个
ivs <- list(taxes,urban,gini,educ,inc,cong))## Put your dataframes into a list
for (i in ivs){
i$state <- tolower(i$state)
}
您可以将 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"
您可以尝试类似的方法:
for( v in ivs){
eval(parse(text=paste0(v,"$state <- tolower(",v,"$state)")))
}
lapply(dflist, function(df) {
df[[1]] <- tolower(df[[1]])
df
})