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