Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export matrix in r

Tags:

r

I want to export a matrix in R (and keep the names of both my rows and columns). When I use write.table or write.csv I get a matrix with a new column. How can I use this function.

Thank you for your help.

like image 618
Delphine Avatar asked Jul 27 '11 12:07

Delphine


People also ask

How do I export a matrix file in R?

The R base function write. table() can be used to export a data frame or a matrix to a file. x: a matrix or a data frame to be written. file: a character specifying the name of the result file.


2 Answers

You don't get a new column, the row names are saved as a first column in the text file. So either you specify the column where the row names are given in read.table, or use the row.names=FALSE option in write.table.

Demonstration :

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")
like image 195
Joris Meys Avatar answered Oct 23 '22 12:10

Joris Meys


I assume that by "new column" you mean the row names that get written out by default. To suppress them, set row.names = FALSE when calling write.table or 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’.
like image 2
NPE Avatar answered Oct 23 '22 14:10

NPE