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

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

    For anyone working in the tidyverse (dplyr, etc.), the rownames_to_column() function from the tibble package can be used to easily convert row.names to a column, e.g.:

    library('tibble')
    a = as.data.frame(matrix(1:9, nrow=3, ncol=3, 
                      dimnames=list(LETTERS[1:3], LETTERS[1:3])))
    
    a %>% rownames_to_column('my_id')
    
      my_id A B C
    1     A 1 4 7
    2     B 2 5 8
    3     C 3 6 9
    

    Combining this with the row.names=FALSE option in write.table() results in output with header names for all columns.

提交回复
热议问题