在R脚本语言中,如何编写行文本,例如,下面两行

Hello
World

到一个名为output.txt的文件?


当前回答

Tidyverse版本与管道和write_lines()从阅读器

library(tidyverse)
c('Hello', 'World') %>% write_lines( "output.txt")

其他回答

简单的write.table()怎么样?

text = c("Hello", "World")
write.table(text, file = "output.txt", col.names = F, row.names = F, quote = F)

参数col.names = FALSE和row.names = FALSE确保排除txt中的行名和列名,参数quote = FALSE排除txt中每行开头和结尾的引号。 要将数据读入,可以使用text = readLines("output.txt")。

Tidyverse版本与管道和write_lines()从阅读器

library(tidyverse)
c('Hello', 'World') %>% write_lines( "output.txt")

一个简单的writeLines()是什么?

txt <- "Hallo\nWorld"
writeLines(txt, "outfile.txt")

or

txt <- c("Hallo", "World")
writeLines(txt, "outfile.txt")
fileConn<-file("output.txt")
writeLines(c("Hello","World"), fileConn)
close(fileConn)

我建议:

writeLines(c("Hello","World"), "output.txt")

它比目前公认的答案更简短、更直接。 没有必要做:

fileConn<-file("output.txt")
# writeLines command using fileConn connection
close(fileConn)

因为writeLines()的文档说:

如果con是字符串,则函数调用file获取 在函数运行期间打开的文件连接 调用。

# default settings for writeLines(): sep = "\n", useBytes = FALSE
# so: sep = "" would join all together e.g.