将向量写入垂直列中的文本文件

时间:2017-04-30 23:03:28

标签: r

我有一个单词列表,我想输出到文本文件。例如:

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

这是有效的,但它给了我水平顺序的单词:a,and,book,cat,car in first row,then door,donkey,食人魔,princess,rain in the second row。我希望订单下载列。 (显然,实际列表比这个例子长得多。)

有什么办法吗?

感谢。

2 个答案:

答案 0 :(得分:3)

你可以试试这个:

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

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

将文件写入:

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

它将数据分布在5列中,逐列写入条目。

答案 1 :(得分:0)

解决方案在这里:Write lines of text to a file in R。基于此:

fileConn <- file("test.out")    
writeLines(c("a", "and", "book", "cat", "car", "door", "donkey", "ogre", "princess", "rain"), fileConn)    
close(fileConn)