【问题标题】:for loop in list.files function produces result only for the last i (R)list.files 函数中的 for 循环仅对最后一个 i (R) 产生结果
【发布时间】:2014-06-08 04:09:26
【问题描述】:

我有一个目录,其中包含两个 .csv 文件,我想读取并导入到 R 中。

到目前为止,我已经尝试了下面实际有效的代码。但仅适用于其中一个文件。

for (i in list.files(path = ".", pattern = "\\.csv$")){
    print(i)
    f <- read.table(i, fill=TRUE, row.names=NULL)
    Table <- data.frame(f[3])
    Table["station.id"] <- i
}
Table

生产

      V3 station.id
1   8.27  agrin.csv
2   9.11  agrin.csv
3  11.60  agrin.csv
4  15.30  agrin.csv
5  20.53  agrin.csv
6  25.07  agrin.csv
7  27.42  agrin.csv
8  27.11  agrin.csv
9  22.92  agrin.csv
10 17.98  agrin.csv
11 13.15  agrin.csv
12  9.62  agrin.csv
13 17.34  agrin.csv

我想要的是实现一个for 循环,它将迭代目录并为里面的每个文件创建一个如上所示的表。

请注意,print(i) 行返回两个结果,例如 agrin.csvagr.csv

有什么建议吗?

【问题讨论】:

    标签: r csv for-loop read.table


    【解决方案1】:

    您没有指定Table$station.id 的行索引,因此最后一个值最终会覆盖整个列。试试这个:

    file.names <- list.files(path = ".", pattern = "\\.csv$")
    Table <- data.frame(V3=rep(NA, length(file.names)), 
                        station.id=rep(NA, length(file.names)))
    for (i in seq_along(file.names)){
        print(file.names[i])
        f <- read.table(file.names[i], fill=TRUE, row.names=NULL)
        Table[i, "V3"] <- f[3]     ## this only works if f has only one observation.
        Table[i, "station.id"] <- file.names[i]
    }
    Table
    

    【讨论】:

    • 更正:for (i in seq_along(file.names))
    • req_along 某个包的一部分吗?我收到could not find function req_along
    • 这将是我个人对seq_along() 的实现。修改回复使用正式版:-)
    • 您是否从循环体中删除了Table &lt;- data.frame(..) 定义?您正在重写每次迭代的数据。
    • 现在我迷路了。请更新答案,以便我们有共同话题:)
    【解决方案2】:

    for 循环之前,让:

     Table <- data.frame(V3=numeric(0), station.id=character(0))
    

    这称为对象预分配。 然后,在循环中,尝试使用rbind。 使用此方案,您将增量地创建对象

    【讨论】:

    • 为什么在循环开始前设置表格很重要?
    • 否则,您将在每次循环迭代中处理一个新对象。在这里,您想“继续”对现有对象进行计算。换句话说,您正在增量创建Table,在每个迭代中添加更多数据。
    猜你喜欢
    • 2020-05-11
    • 2019-02-08
    • 1970-01-01
    • 2020-11-22
    • 2018-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多