【问题标题】:Filter operation with for loop in R在 R 中使用 for 循环进行过滤操作
【发布时间】:2021-06-09 20:38:53
【问题描述】:

我想将下面的代码应用于 21 个 csv 文件,并将它们像这个问题一样放在数据框中,一个接一个地作为 data.frame; add one column below another in a data.frame in R 我怎样才能像循环一样应用它?有什么建议吗??

H1 <- csv_group %>%
  select(Group.1, harvest, crop,plot, chm_H1)%>%
  filter(harvest==1)

【问题讨论】:

  • 可能的方法:使用list.files()将文件加载到列表中,并使用mylist &lt;- lapply( myfiles, data.table::fread, ...)行执行读取操作,然后将列表行绑定到一个data.table,例如data.table::rbindlist( mylist, ...)

标签: r filter dplyr


【解决方案1】:

这可以使用 for 循环完成,并事先进行少量设置:

path_to_files = "c:/folder/subfolder"
list_of_files_to_read = c("file1.csv", "file2.csv", ...)

output = data.frame()

# loop through files
for(file in list_of_files_to_read){
  # load each file
  this_file_full_path = paste0(path_to_files,"/",file)
  this_file_contents = read.csv(this_file_full_path)

  # filter as required
  prepared_df = this_file_contents %>%
      select(Group.1, harvest, crop,plot, chm_H1)%>%
      filter(harvest==1)

  # append to output
  output = rbind(output, prepared_df)
}

【讨论】:

    猜你喜欢
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-30
    相关资源
    最近更新 更多