4

I am trying to save a matrix that I have in R as a text file that is tab-delimited with the row and column names included and properly aligned.

I have tried this:

write.table(data, "mytable.txt", sep="\t", col.names=TRUE)

But when I open the file it is a jumbled up mess. I assume it has something to do with my row or column names not being specified, but I am unsure.

Wolfpack
  • 59
  • 2
  • 7
  • I'm very new to R so I'm not even sure how the post @TimBiegeleisen listed helps me. I understand they are both similar but I am still not able to solve my problem from that post. I am also not sure how to redirect print() or what exactly that means. – Wolfpack Sep 29 '15 at 02:20

2 Answers2

2

You can use the following code, which will write output of your matrix to file using the neat format you see when you print from the R console:

max.print <- getOption('max.print')
options(max.print=nrow(data) * ncol(data))
sink('data.txt')
data
sink()
options(max.print=max.print)

Look for an output file called data.txt. To find the location, do File -> Open script from your R console. It should be visible in the directory in which the dialog box opened.

Disclaimer: I basically cut-and-pasted this code from this SO post, of which your question is really a duplicate.

Community
  • 1
  • 1
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

From write.table help page concerning CSV (also tab-separated) files:

CSV files. By default there is no column name for a column of row names. If col.names = NA and row.names = TRUE a blank column name is added

Since row.names = TRUE is the default, if you change col.names=TRUE to col.names=NA, your output should be in the proper alignment.

pcantalupo
  • 2,212
  • 17
  • 27