简体   繁体   English

在 R 中循环多个数据帧

[英]Looping multiple data frames in R

I am wondering whether it's possible to loop data frames and change the contents of each field.我想知道是否可以循环数据帧并更改每个字段的内容。

There are dataframes like df1, df2, df3, ... df100有 df1, df2, df3, ... df100 等数据帧

In each dataframe, there are food columns having a, b在每个 dataframe 中,有食物列具有 a、b

I want to change each a and b in df$food to apple, banana!我想将df$food中的每个 a 和 b 更改为苹果、香蕉!

for (i in 1:100){
    paste('df', i, '$food') <- factor(paste('df', i, '$food'), level = c(a,b), labels = c("apple","banana"))
}

Do you think looping like above is possible?你认为像上面这样的循环是可能的吗?

It would be easier if you put them in a list of dataframes and use lapply .如果将它们放在数据框列表中并使用lapply会更容易。

result <- lapply(mget(paste0('df', 1:100)), function(x) transform(x, 
             food = factor(food, level=c("a","b"), labels=c("apple","banana"))))

Update the original dataframes back.更新原始数据帧。

list2env(result, .GlobalEnv)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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