2011-07-27 117 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'已經足夠... –