简体   繁体   中英

adding blank field AND column names in write.table

I am using write.table to output a matrix as a .txt file. I am trying to add a blank column for the rownames AND to add the column names subsequently with the col.names argument. I have seen lots of answers to how to do either one or the other, but none showing how to do both. (It is easy to fix manually afterwards, but if others are to be able to make sense of my script (which is about 1500 lines long and written for a scientific publication), I would very much like to have it all contained within the R code).

I know that a blank column name is added if col.names = NA and row.names = TRUE. However, I wish to use the col.names argument like this

write.table(x,"~/Desktop/Folder/myfile_x.txt",sep="\t",
row.names=TRUE,col.names=c("\",\"Name1","Name2","Name3",....) 

This gives me an output like this

\,\"Name1"  Name2   Name3...
rowname1    0   0
rowname2    3   2
rowname3    3   7

where I would like

[BLANK] Name1   Name2...    
rowname1    0   0
rowname2    3   2
rowname3    3   7

where the first column name (for the rownames/numbers) is a blank field.

I know I could try a workaround with paste(), but if it is possible with col.names, it would be MUCH easier. Thanks in advance!

Please help me understand your question better if below is irrelevant or does not help. I think that you are just looking to have the rownames as a column, which has "" colname so to say.. And in this case, you don't need the row.names in write.table:

library(dplyr)
data("mtcars")
cbind(rownames(mtcars), mtcars) -> mtcars.nm
colnames(mtcars.nm)<-c("", colnames(mtcars))
mtcars.nm %>% 
  write.table(x=., file="tmp.txt", sep="\t", quote=FALSE, row.names=FALSE)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM