如何使用R将数据写入现有文件的特定列?

时间:2014-11-18 23:41:17

标签: r

我有一个名为otu的文件有很多列。在文件otu中,我想将一列数据附加到特定的现有列中并将其写入文件中。要附加的数据来自文件,映射,并且映射中的每一行都应作为列添加到文件otu中的相应列中。如果地图中不存在该行,我希望不附加任何内容。

到目前为止,我已经创建了一个名为newCol的向量,它包含文件otu特定顺序中列的数据。我希望能够编写向量newCol中包含的特定列,并将其写入文件otu中的现有列。

我也理解newCol是一个向量,想知道我应该用什么数据类型来保存列,以及如何将列写入文件otu中的特定现有列。

到目前为止,我已经创建了向量newCol,它以正确的顺序保存我的所有数据。

#newCol holds columns of data copied from file named "map"
newCol<-c()
#Loop over the columns of the file named "otu"
for (col in colnames(otu)){
  #check if each column header col is a row name of the file "map"
  if (is.element(col, rownames(map))){
    #if True, the row of name col in file map should be transposed and concatenated to variable newCol
    newCol<- c(newCol, t(map[col,]))

  #if False, concatenate "" because the row name col does not exist as a row in the map file

    }else{
    #if the col is not in the header, NA is added
    newCol<- c(newCol, "")

    }

}

所以,我试图将otu文件复制到名为newOTU的新变量中,附加到newOTU的列,然后将整个newOTU打印到新文件中。

但是我收到错误newOTU [,col]:维数不正确。

#newCol holds columns of data copied from file named "map"
newOTU <- otu
newCol<-c()
#Loop over the columns of the file named "otu"
for (col in colnames(otu)){
  #check if each column header col is a row name of the file "map"
  if (is.element(col, rownames(map))){
    #if True, the row of name col in file map should be transposed and concatenated to column col in newOTU
    newOTU[,col] <- append(newOTU[,col], t(map[col,]))

    }

}
write.table(newOTU, file = "test.txt", append = FALSE, quote = TRUE, sep = "\t",
        eol = "\n", na = "NA", dec = ".", row.names = TRUE,
        col.names = TRUE)

0 个答案:

没有答案