1
如何在数据框中附加列?动态追加列到数据框R
我在遍历我的数据矩阵,并且如果某些数据与我设置的阈值一致,我想将它们存储在一行数据框中,以便可以在循环结束时进行打印。
我的代码,如下所示:
for (i in 1:nrow(my.data.frame)) {
# Store gene name in a variable and use it as row name for the 1-row dataframe.
gene.symbol <- rownames(my.data.frame)[i]
# init the dataframe to output
gene.matrix.of.truth <- data.frame(matrix(ncol = 0, nrow = 0))
for (j in 1:ncol(my.data.frame)) {
if (my.data.frame[i,j] < threshold) {
str <- paste(colnames(my.data.frame)[j], ';', my.data.frame[i,j], sep='')
# And I want to append this str to the gene.matrix.of.truth
# I tried gene.matrix.of.truth <- cbind(gene.matrix.of.truth, str) But didn't get me anywhere.
}
}
# Ideally I want to print the dataframe here.
# but, no need to print if nothing met my requirements.
if (ncol(gene.matrix.of.truth) != 0) {
write.table(paste('out_',gene.symbol,sep=''), gene.matrix.of.truth, row.names = T, col.names = F, sep='|', quote = F)
}
}
'cbind'将不起作用,因为你基本上试图将“一行数据框”(即'str')连接到零行的数据框(即'gene.matrix.of.truth')。我在下面提出了一个解决方案,在这个解决方案中绑定行而不是列:我希望它有帮助 – lebelinoz