2011-07-27 118 views
6

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

谢谢你的帮助。

回答

11

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

示范:

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

+1不用于复制帮助文件 –

+3

不需要粗鲁的 - 例如我没有检查文档,但对于write.matrix,并没有这样的选项 –

2

我假设“新列”是指默认情况下写出的行名。要取消它们,请在致电write.tablewrite.csv时设置row.names = FALSE

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’. 
+0

hehe,+1用于实际复制帮助文件。但''write.table'已经足够... –