【发布时间】: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
我完全无法让它工作 - 手动连接文件是一种痛苦!
【问题讨论】:
-
你是
rbindingdat_i什么都没有,最简单的解决方案是pesto <<- rbind(pesto, dat_i)。 -
就是这样!!!!!!!!!!非常感谢。
-
等等,我有一个更好的答案。
标签: r loops dataframe concatenation