【问题标题】:Loading files from multiple folders in r and processing从r中的多个文件夹加载文件并处理
【发布时间】:2021-05-12 07:45:12
【问题描述】:

我在不同的文件夹中有多个 csv 文件,即主文件夹包含第 1 周和第 2 周文件夹。第 1 周依次包含 file1.csv,第 2 周包含 file2.csv。所有文件都有相同的列名。在不同的目录中有 100 个这样的文件

file1 <- data.frame(name = c("Bill","Tom"),Age = c(23,45))
file2 <- data.frame(name = c("Harry","John"),Age = c(34,56)) 

如何加载它们并在 r 中执行 rbind 并将它们放入最终数据帧中

我在这里得到了一些线索:How can I read multiple files from multiple directories into R for processing?

我所做的是对函数进行轻微修改以进行如下的行绑定,但与我想要的相去甚远

 # Creating a function to process each file
 empty_df <- data.frame()
 processFile <- function(f) {
 df <- read.csv(f)
 rbind(empty_df,df)
 }

# Find all .csv files
files <- dir("/foo/bar/", recursive=TRUE, full.names=TRUE, pattern="\\.csv$")

# Apply the function to all files.
result <- sapply(files, processFile)

非常感谢任何帮助!

【问题讨论】:

    标签: r


    【解决方案1】:

    我会尝试使用 for 循环来做一些事情,例如

    temp = read.csv('week1/file1.csv')
    
    for(i in 2:n){ #n being the number of weeks you have
      temp= rbind(temp, read.csv(paste('week',i,'/file',i,'.csv', sep='')))
      }
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多