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

前端 未结 5 1189
-上瘾入骨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条回答
  •  Happy的楠姐
    2020-12-07 09:45

    I revised a simple function from @mnel, which adds flexibility by using connections. Here is the function:

    my.write <- function(x, file, header, f = write.csv, ...){
    # create and open the file connection
    datafile <- file(file, open = 'wt')
    # close on exit 
    on.exit(close(datafile))
    # if a header is defined, write it to the file (@CarlWitthoft's suggestion)
    if(!missing(header)) {
    writeLines(header,con=datafile, sep='\t')
    writeLines('', con=datafile, sep='\n')
    }
    # write the file using the defined function and required addition arguments  
    f(x, datafile,...)
    }
    

    You can specify the function to be 'write.table', 'write.csv', 'write.delim' etc.

    Cheers!

提交回复
热议问题