【问题标题】:How Can I Merge Multiple Files with Unequal Rows in R如何在 R 中合并具有不相等行的多个文件
【发布时间】:2015-03-20 18:09:33
【问题描述】:

我有大约 100 个包含两列和大约 320-500 行的文本文件,我想合并到一个 .csv 文件中。

例如,我的文件 A 看起来像这样
甲乙
1 100
2 200
3 300
4 400

和文件 B 看起来像这样
甲乙
1 100
2 200
3 300
4 400
5 300
6 400

但是,当我将此代码输入 R 时:write.csv (data_list, ("file.csv"), row.names = FALSE, na="")
我收到此错误消息:"Error in data.frame(list(V1 = c(0.025, 0.035, 0.045, 0.055, 0.065, 0.075, : arguments imply differing number of rows: 500, 599, 508, 489, 547, 624, 587, 534, 499, 494, 566, 520, 541, 543, 615"


我希望我的文件看起来像这样(一个将我的所有 100 个文本文件按两列组合在一起的文件):
档案 AB
甲乙
1 100
2 200
3 300
4 400
1 100
2 200
3 300
4 400
5 300
6 400
在一个巨大的 csv 文件中。如果可能,请帮助我。我是脚本新手,如有需要,我会提供更多信息。

【问题讨论】:

  • 那么你有没有把数据读入R?因为您的代码使用write.csvdata_list 是 data.frames 的列表吗?你想先把它组合成一个更大的data.frame吗?你从dplyr 看过rbind_list 吗?这应该会更容易(因为你实际上只是“绑定”而不是“合并”)
  • 是的,我有。 data_list 是我想用来创建 csv 文件的所有文件。我刚刚尝试了rbind_list,它可以绑定文件的名称,但我想绑定所有这些文件的内容。抱歉,我不确定我是否解释正确!
  • 你能显示你使用的代码吗?如果A, B 是对象,bind_rows(A,B) 会得到你显示的结果。
  • 当然! setwd("/directory") datafiles <-list.files (pattern='*.file.txt') data_list = lapply (datafiles, read.table, header=FALSE) write.csv (data_list, ("/directory/file.csv"), row.names = FALSE, na="")
  • bind_rows(data_list) 的结果是什么? (假设您使用新的 dplyr 版本)。顺便说一句,您在列表中使用write.csv

标签: r csv merge export-to-csv


【解决方案1】:

这是实现它的不同选择。

R 代码:

# Option 1: Using plyr
library(plyr)
datafiles <-list.files (pattern='*.txt') 
dataset <- ldply(datafiles, read.table, header=F)

# Option 2: Using fread
library(data.table)
datafiles <-list.files (pattern='*.txt') 
dataset = rbindlist(lapply( datafiles, fread, header=F))

# Option 3: do.call method
dataset <- do.call("rbind",lapply(datafiles,
                              FUN=function(files){read.table(files,
                                                             header=FALSE)}))

# Option 4: Loops are any time slow so avoid, but have put here just for reference
for (file in datafiles){  
  # if the merged dataset doesn't exist, create it
  if (!exists("dataset")){
    dataset <- read.table(file, header=FALSE)
  }

  # if the merged dataset does exist, append to it
  if (exists("dataset")){
    temp_dataset <-read.table(file, header=FALSE)
    dataset<-rbind(dataset, temp_dataset)
    rm(temp_dataset)
  }  
}

# Writing to csv
write.csv (dataset, ("file.csv"), row.names = FALSE, na="") 

【讨论】:

  • 其中任何一个都不需要header arg。在read.table 中,它默认为FALSE。并且不需要lapply() 中的匿名函数。你可以做do.call(rbind, lapply(datafiles, read.table))
【解决方案2】:

我认为使用 dplyr 或 plyr 包函数真的是大材小用。建议尝试 write.table,(因为所需输出中没有逗号):

write.table(file_A, file="comb_file.txt")
write.table(file_B, file="comb_file.txt", append=TRUE)

您当然可以使用write.csv,但输出看起来不像您所说明的那样。

【讨论】:

    猜你喜欢
    • 2018-01-03
    • 1970-01-01
    • 2015-06-28
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 2014-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多