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

前端 未结 5 1191
-上瘾入骨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:44

    A slight modification to @Marek very helpful answer WILL add a header to the rownames column: temporarily add the rownames as the first column in the data.frame, and write that, ignoring the real rownames.

    > a = matrix(1:9, nrow = 3, ncol = 3, dimnames = list(LETTERS[1:3], LETTERS[1:3]))
    > write.table(data.frame("H"=rownames(a),a),"a.txt", row.names=FALSE)
    

    and you get

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

提交回复
热议问题