【问题标题】:Importing and merging .csv files with loop in R在 R 中使用循环导入和合并 .csv 文件
【发布时间】:2018-12-13 13:56:30
【问题描述】:

我有 20 个名为 1.csv、2.csv、3.csv 等的文件,我想将它们读入 R 并使用 rbind 使用循环进行合并。 我已经尝试了下面的代码,但我收到一条错误消息,在第二行中显示意外的“[”。

for (i in 1:22) {
  fish[i]  <- read.csv([i].csv)
  combined <- rbind(fish[i], fish[i+1])
}

【问题讨论】:

  • 试试fish[i] &lt;- read.csv(paste0(i, ".csv"))
  • 如果你只有 20 个文件,你的循环应该只有 1:20 我想。
  • 感谢您这么快回复
  • for (i in 1:22) { fish[i]
  • 我试过这个但我得到了错误:找不到对象'fish'

标签: r loops csv


【解决方案1】:

将我的评论放在答案中:

# just for rbindlist, there are also base ways to do this
library(data.table)

fish <- list()
for (i in 1:20) {
  fish[[i]] <- read.csv(paste0(i, ".csv"))
}
combined <- rbindlist(fish)

替代方案: 与 data.frames 上的 do.call("rbind", fish) 相同,但要快得多。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 2015-04-14
    • 1970-01-01
    • 2019-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多