3

I have a list of words, which I want to output to a text file. For example:

words <- c("a", "and", "book", "cat", "car", "door", "donkey", "ogre", "princess", "rain")
write(words, file = "test.out", ncolumns = 5, sep = "\t")

This works, but it gives me the words in order horizontally: a, and, book, cat, car in the first row, then door, donkey, ogre, princess, rain in the second row. I want the order to go down columns. (Obviously, the actual list is much longer than this example).

Any way to do that?

Thanks.

Steve Scher
  • 144
  • 1
  • 12

2 Answers2

4

Solution is here: Write lines of text to a file in R. Based on it:

fileConn <- file("test.out")    
writeLines(c("a", "and", "book", "cat", "car", "door", "donkey", "ogre", "princess", "rain"), fileConn)    
close(fileConn)
  • 1
    `close` will return an error because **`writeLines` already closes the connection**. From `?writeLines`: "If the connection is open it is written from its current position. If it is not open, it is opened for the duration of the call in 'wt' mode and then closed again." –  Dec 06 '18 at 09:29
4

You can try this:

nc <- 5
nr <- length(words) / nc

mwords <- matrix(words, nr, nc)
write.table(mwords, "test.csv", row.names = FALSE, col.names=FALSE, sep = "\t")

which writes to the file as:

"a" "book"  "car"   "donkey"    "princess"
"and"   "cat"   "door"  "ogre"  "rain"

It spreads the data in 5 columns, writing the entries column-wise.

Aramis7d
  • 2,444
  • 19
  • 25