r中的导出矩阵

时间:2011-07-27 12:20:02

标签: r

我想在R中导出矩阵(并保留我的行和列的名称)。当我使用write.table或write.csv时,我得到一个带有新列的矩阵。我该如何使用这个功能。

感谢您的帮助。

2 个答案:

答案 0 :(得分:12)

我没有看到问题。您没有获得新列,行名称将保存为文本文件中的第一列。因此,要么指定read.table中给出行名称的列,要么使用row.names=FALSE中的write.table选项。

示范:

mat <- matrix(1:10,ncol=2)
rownames(mat) <- letters[1:5]
colnames(mat) <- LETTERS[1:2]

mat
write.table(mat,file="test.txt") # keeps the rownames
read.table("test.txt",header=TRUE,row.names=1) # says first column are rownames
unlink("test.txt")
write.table(mat,file="test2.txt",row.names=FALSE) # drops the rownames
read.table("test.txt",header=TRUE) 
unlink("test2.txt")

在任何情况下,阅读帮助文件都会告诉你所有这些。

答案 1 :(得分:2)

我认为“新列”是指默认写出的行名。要取消它们,请在致电row.names = FALSEwrite.table时设置write.csv

write.table               package:utils                R Documentation

Data Output

Description:

     ‘write.table’ prints its required argument ‘x’ (after converting
     it to a data frame if it is not one nor a matrix) to a file or
     connection.

Usage:

     write.table(x, file = "", append = FALSE, quote = TRUE, sep = " ",
                 eol = "\n", na = "NA", dec = ".", row.names = TRUE,
                 col.names = TRUE, qmethod = c("escape", "double"))

     write.csv(...)
     write.csv2(...)

...

row.names: either a logical value indicating whether the row names of
          ‘x’ are to be written along with ‘x’, or a character vector
          of row names to be written.

col.names: either a logical value indicating whether the column names
          of ‘x’ are to be written along with ‘x’, or a character
          vector of column names to be written.  See the section on
          ‘CSV files’ for the meaning of ‘col.names = NA’.