Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write.table writes unwanted leading empty column to header when has rownames

check this example:

> a = matrix(1:9, nrow = 3, ncol = 3, dimnames = list(LETTERS[1:3], LETTERS[1:3])) > a   A B C A 1 4 7 B 2 5 8 C 3 6 9 

the table displays correctly. There are two different ways of writing it to file...

write.csv(a, 'a.csv') which gives as expected:

"","A","B","C" "A",1,4,7 "B",2,5,8 "C",3,6,9 

and write.table(a, 'a.txt') which screws up

"A" "B" "C" "A" 1 4 7 "B" 2 5 8 "C" 3 6 9 

indeed, an empty tab is missing.... which is a pain in the butt for downstream things. Is this a bug or a feature? Is there a workaround? (other than write.table(cbind(rownames(a), a), 'a.txt', row.names=FALSE)

Cheers, yannick

like image 667
Yannick Wurm Avatar asked Mar 19 '10 15:03

Yannick Wurm


1 Answers

Citing ?write.table, section CSV files:

By default there is no column name for a column of row names. If col.names = NA and row.names = TRUE a blank column name is added, which is the convention used for CSV files to be read by spreadsheets.

So you must do

write.table(a, 'a.txt', col.names=NA) 

and you get

"" "A" "B" "C" "A" 1 4 7 "B" 2 5 8 "C" 3 6 9 
like image 168
Marek Avatar answered Oct 06 '22 09:10

Marek