【问题标题】:Iteratively concatenating and labelling data frames in R在 R 中迭代地连接和标记数据帧
【发布时间】:2018-01-22 16:44:16
【问题描述】:

我正在尝试在 R 中编写一个 for 循环,该循环从目录中读取文件名列表,将它们转换为数据帧,并将它们连接成一个大数据帧,同时为每个数据帧添加一个标识符,以便我知道绘图时哪个文件生成了哪些数据。到目前为止,我有一个 for 循环运行在一个函数上,该函数将每个数据帧附加到我早期初始化的空数据帧,如下所示:

filenames <- list.files(path="reads/metrics", pattern="*.txt", all.files=T, recursive=FALSE, full.names = TRUE)
n= 0
pesto = data.frame(size=character(), fcount= character(),rcount=character(), total = character(), Identifier= character())

concat = function(filename, n){
    dat = read.table(filename, header=TRUE, na.strings="EMPTY")
    dat_i = transform(dat, Identifier = rep((paste("time", n, sep="")), nrow((dat))))
    pesto <<- rbind(dat_i)
}

for (f in filenames) {
n = n+1
concat(f, n)
}

所以对于两个示例数据帧,读入后如下所示:

> df1 (from file of Time = 1)
         size     fcount     rcount   total
[1,]       1        2           3         5
[2,]       4        1           1         2
[3,]       5        1           2         3

> df2 (from file of Time = 2)
         size     fcount     rcount   total
[1,]       1        3           6         9
[2,]       3        1           5         6
[3,]       5        1           2         3

所需的输出看起来像,

> pesto
         size     fcount     rcount   total    Identifier
[1,]       1        2           3         5        time1
[1,]       1        3           6         9        time2
[2,]       3        1           5         6        time2
[2,]       4        1           1         2        time1
[3,]       5        1           2         3        time1
[3,]       5        1           2         3        time2

相反,我的输出只是 df2,但带有标签!

到目前为止,在调试过程中,我已经询问了 print(n) 函数,以确保我在循环中正确地迭代并且它给了我正确的输出:

[1] 1
[1] 2

我完全无法让它工作 - 手动连接文件是一种痛苦!

【问题讨论】:

  • 你是rbinding dat_i 什么都没有,最简单的解决方案是pesto &lt;&lt;- rbind(pesto, dat_i)
  • 就是这样!!!!!!!!!!非常感谢。
  • 等等,我有一个更好的答案。

标签: r loops dataframe concatenation


【解决方案1】:

您可以不用for 循环,而是使用lapply。 (我知道*apply 函数是伪装的循环,但它们通常被认为更好R 代码。)

files_list <- lapply(filenames, read.table, header=TRUE, na.strings="EMPTY")
pesto <- lapply(seq_along(files_list), function(n){
                x <- files_list[[n]]
                x$Identifier <- paste0("time", n)
                x
            })
pesto <- do.call(rbind, pesto)
pesto <- pesto[order(pesto$size), ]
pesto

【讨论】:

  • 这非常有用,而且是一种更清洁的做事方式。谢谢!
猜你喜欢
  • 2013-12-05
  • 2014-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多