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

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

    For those who experience the same issue when saving a matrix with write.table() and want to keep the row.names column, there is actually an extremely simple solution:

     write.table(matrix,file="file.csv",quote=F,sep=";", row.names=T
                 col.names=c("row_name_col;val1_col","val2_col"))
    

    By doing that you're basically tricking the write.table function into creating a header label for the row.names column. The resulting .csv file would look like this:

    row_name_col;val1_col;val2_col
    row1;1;4 
    row2;2;5 
    row3;3;6 
    

提交回复
热议问题