2017-05-18 72 views
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) 
    }   
} 
+0

'cbind'将不起作用,因为你基本上试图将“一行数据框”(即'str')连接到零行的数据框(即'gene.matrix.of.truth')。我在下面提出了一个解决方案,在这个解决方案中绑定行而不是列:我希望它有帮助 – lebelinoz

回答

1

我做这样的事情所有的时间,但随着行而不是列。开始于

gene.matrix.of.truth = data.frame(x = character(0)) 

而不是你在开始时的gene.matrix.of.truth <- data.frame(matrix(ncol = 0, nrow = 0))。在for j环内,您的附加步骤将是

gene.matrix.of.truth = rbind(gene.matrix.of.truth, data.frame(x = str)) 

(即创建一个数据框周围str并追加到gene.matrix.of.truth)。

显然,最终的if语句将if(nrow(...))代替if(ncol(...)),如果你想在决赛桌一大排,你需要在t打印时间来转您的数据帧。