【问题标题】:How to write a R loop to add multiple excel files, change their column names, and then combine them based on one row?如何编写一个R循环来添加多个excel文件,更改它们的列名,然后基于一行组合它们?
【发布时间】:2021-06-20 16:45:19
【问题描述】:

这里是初学者,我有 31 个 excel 文件要提取数据框。我想要一个 R 循环来读取所有文件,然后只取 2 列并更改列名。然后我想根据同一行合并文件。

这是我的尝试:

files = list.files(path=".", pattern="xls")
for (i in 1:length(files)){
  table = data.frame(readxl::read_xls(files[i]), stringsAsFactors=FALSE)
  table = table[,c(1,3)]
  colnames(table) = c("UR",paste0("Zscore",i))
    } 
  }
}

问题是我不知道如何编写代码来保存单个文件。此代码仅保存最后一个文件。我整晚都在谷歌上搜索,但无法弄清楚。 我也尝试了 assign() 但我不知道如何在循环中修改分配中的表。

files = list.files(pattern="*.xls")
for (i in 1:length(files))assign(files[i], data.frame(readxl::read_xls(files[i])))

我希望文件最终像 UR、Zscore1、Zscore2、Zscore3...

So instead I did it manually like this:
table1 = data.frame(readxl::read_xls(files[1]), stringsAsFactors=FALSE)
table1 = table1[,c(1,3)]
colnames(table1) = c("UR",paste0("Zscore",1))


table2 = data.frame(readxl::read_xls(files[2]), stringsAsFactors=FALSE)
table2 = table2[,c(1,3)]
colnames(table2) = c("UR",paste0("Zscore",2))
tableA = merge(table1,table2, all.x = T)


table3 = data.frame(readxl::read_xls(files[3]), stringsAsFactors=FALSE)
table3 = table3[,c(1,3)]
colnames(table3) = c("UR",paste0("Zscore",3))
tableA = merge(tableA,table3, all.x = T)

【问题讨论】:

    标签: r excel loops


    【解决方案1】:

    主要问题是您没有将表分配给任何东西,因此您在每次迭代时都重建表。

    对于每次迭代,您应该使用分配运算符将创建的表分配为数据框或列表的相应元素 [[i]]

    也许这样的事情会起作用:

    files <- list.files(path=".", pattern="xls")
    list_of_tables<-vector(mode = "list", length = (length(files))
    
    for (i in seq_along(files)){
      list_of_tables[i] <- data.frame(readxl::read_xls(files[i]), stringsAsFactors=FALSE)[,c(1,3)]
      names(list_of_tables[i]) <- c("UR",paste0("Zscore",i))
    } 
    
    

    然后,如果你想将整个列表堆叠在一个数据框中,你可以使用 cbind,如:

    my_data_frame<-do.call(cbind, list_of_tables)
    

    否则就将其保留为列表

    【讨论】:

    • 我尝试运行您的代码。但它一直说“错误:路径不存在:‘NA’。”不知道出了什么问题。
    • 刚刚编辑了for循环,也许现在可以工作了
    • 如果您显示“错误:路径不存在”,请确保您在 list.files(path="here_your_files_path", pattern="xls") 中拥有正确的文件路径
    • 我有正确的路径,因为我能够从第一行获取文件名列表。现在它给了我错误“在 list_of_tables[i]
    • 空列表被创建为只有一个元素的列表。已更正。
    【解决方案2】:

    lapplyReduce 试试这个方法:

    files = list.files(path=".", pattern="xls")
    
    Reduce(function(x, y) merge(x, y, all.x = T, by = 'UR'), 
            lapply(seq_along(files), function(i) {
                  data <- readxl::read_xls(files[i])
                  data <- data[c(1, 3)]
                  names(data) <- c('UR', paste0('Zscore', i))
                  data
    })) -> result
    
    result
    

    【讨论】:

    • 我试过你的代码。但是在 merge.data.frame(x, y, all.x = T, by = "UR") 中出现错误:不允许负长度向量
    • 我得到了删除 all.x=T 的代码。不知道为什么
    猜你喜欢
    • 2022-08-22
    • 2013-09-25
    • 2021-11-28
    • 2022-12-04
    • 1970-01-01
    • 2019-12-10
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    相关资源
    最近更新 更多