1
votes

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!

1
If you just use col.names = c("Name1","Name2","Name3"), while it shows Name1 over row names in the text file, when you read it in, you will see that Name1 is actually the name of the first column and the column containing rownames has no name. It's just the index.ytk
Teja is also right btw, however, the problem is that there is not going to be a "\t" before the colnames in the output file. In other words, having opened the file in spreadsheet or excel say, you will have to (as you mention above) insert a cell to shift the column names one cell to the right.AlexT

1 Answers

0
votes

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)