R-遍历多个数据帧

with two or more dataframes, df1, df2, df3, df4, ... what data structure should be used such that it is possible to iterate through the dataframes and do something with each.

for(df in 'what') {
  print(colnames(df))
}

the what part - which data structure to be used so that each dataframe can be accessed to do something with it in side the for loop.

评论
  • kquam
    kquam 回复
    library(tidyverse)
    for(df in list(band_instruments, iris, mtcars)){
    
      print(colnames(df))
    }
    
    # [1] "name"  "plays"
    # [1] "Sepal.Length" "Sepal.Width"  "Petal.Length" "Petal.Width"  "Species"     
    # [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear" "carb"
    
  • 我呸!
    我呸! 回复

    通常,最好将数据包含在列表中,而不要在全局环境中使用单独的数据框。将数据保存在列表中更易于管理。

    list_df <- mget(ls(pattern = 'df\\d+'))
    

    and use lapply to do something on each one of it.

    lapply(list_df, function(x) names(x))