在R脚本语言中,如何编写行文本,例如,下面两行
Hello
World
到一个名为output.txt的文件?
在R脚本语言中,如何编写行文本,例如,下面两行
Hello
World
到一个名为output.txt的文件?
当前回答
fileConn<-file("output.txt")
writeLines(c("Hello","World"), fileConn)
close(fileConn)
其他回答
简单的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")。
为了完善可能性,你可以使用writeLines()和sink(),如果你想:
> sink("tempsink", type="output")
> writeLines("Hello\nWorld")
> sink()
> file.show("tempsink", delete.file=TRUE)
Hello
World
对我来说,使用print()似乎总是最直观的,但如果你这样做,输出将不是你想要的:
...
> print("Hello\nWorld")
...
[1] "Hello\nWorld"
我将使用cat()命令,如下例所示:
> cat("Hello",file="outfile.txt",sep="\n")
> cat("World",file="outfile.txt",append=TRUE)
然后,您可以使用R with查看结果
> file.show("outfile.txt")
hello
world
Tidyverse版本与管道和write_lines()从阅读器
library(tidyverse)
c('Hello', 'World') %>% write_lines( "output.txt")
用R语言将文本行写入文件的简单方法可以通过cat或writeLines实现,正如在许多答案中已经展示的那样。一些最短的可能性可能是:
cat("Hello\nWorld", file="output.txt")
writeLines("Hello\nWorld", "output.txt")
如果你不喜欢“\n”,你也可以使用下面的样式:
cat("Hello
World", file="output.txt")
writeLines("Hello
World", "output.txt")
当writeLines在文件末尾添加换行符时,cat则不是这样。 这种行为可以通过以下方法进行调整:
writeLines("Hello\nWorld", "output.txt", sep="") #No newline at end of file
cat("Hello\nWorld\n", file="output.txt") #Newline at end of file
cat("Hello\nWorld", file="output.txt", sep="\n") #Newline at end of file
但主要的区别是cat使用R对象和writeLines一个字符向量作为参数。所以写出例如数字1:10需要被强制转换为writeLines,而它可以像在cat中那样使用:
cat(1:10)
writeLines(as.character(1:10))
and cat可以接受很多对象,但writeLines只能接受一个vector:
cat("Hello", "World", sep="\n")
writeLines(c("Hello", "World"))