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

前端 未结 5 1184
-上瘾入骨i
-上瘾入骨i 2020-12-07 09:22

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
5条回答
  •  时光取名叫无心
    2020-12-07 09:47

    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
    

提交回复
热议问题