在R中的data.frame中添加行和列

时间:2018-06-08 21:01:12

标签: r

我正在努力使用数据框。

我正在计算n个参与者的测试结果,每个参与者都有m个结果。这将在嵌套for循环中完成:n x m。 所以首先For-Loop进入第一个Proband。第二个for循环计算测试值。 1个先证者的1次测试的测试结果从函数返回。

最后我想有一张这样的表:
enter image description here

我很难用数据框和向量设置它,因为我对R来说是全新的。

伪代码:

final_results[][]

for (each folder in path) {
  proband_results[]
  for (each file in folder) {
    test_result <- someFunction(file)
    proband_results.append(test_result)
  }
  final_results.append(proband_results)
}

2 个答案:

答案 0 :(得分:2)

正如Circle 2 of the R Inferno: Growing Objects中所建议的那样,不要使用cbindrbindappend和{{}在循环中扩展特别大的对象,如矩阵/数组和数据框1}}运算符会导致内存中的过多复制。

相反,构建对象列表,然后在迭代之外的一个调用中绑定。或者,初始化一个大的空容器,并按容器索引迭代分配值而不附加。

对于前者,可以使用R的 apply 系列循环来促进该方法,该循环已知输出具有相等长度的对象。对于嵌套在较大c子文件夹中的文件,下面运行sapply假设某个函数接收一个参数为文件名并返回一个向量。

lapply

答案 1 :(得分:1)

根据您的代码有R版本。使用NULL初始化并使用cbindrbind。我假设test_result已经是data.frame类型。

final_results= NULL

for (each folder in path) {
  proband_results = NULL
  for (each file in folder) {
    test_result <- someFunction(file)
    proband_results = cbind(proband_results,test_result)  # column bind 
  }
  final_results = rbind(final_results,proband_results) # row bind
}

然而,这并不是R结合结果的有效方法。因为,例如,在这里你要调用rbind n次,每次调用不断增长的final_results(增长内存)并使用rbind。矢量化方式是(小改进)使用list结构(链表):

final_results= NULL
i = 1
for (each folder in path) {
  proband_results = NULL
  for (each file in folder) {
    test_result <- someFunction(file)
    proband_results = cbind(proband_results,test_result)  # column bind 
  }
  final_results[[i]] = proband_results # A list that link all proband results
  i = i + 1
}

res = do.call("rbind",final_results)  # rbind for all the element in the list

这个版本一次性rbind

相关问题