在R脚本语言中,如何编写文本行,例如以下两行
Hello
World
Run Code Online (Sandbox Code Playgroud)
到名为"output.txt"的文件?
Mar*_*ark 394
fileConn<-file("output.txt")
writeLines(c("Hello","World"), fileConn)
close(fileConn)
Run Code Online (Sandbox Code Playgroud)
aL3*_*3xa 144
实际上你可以用sink():
sink("outfile.txt")
cat("hello")
cat("\n")
cat("world")
sink()
Run Code Online (Sandbox Code Playgroud)
因此:
file.show("outfile.txt")
# hello
# world
Run Code Online (Sandbox Code Playgroud)
小智 106
我将使用cat()此示例中的命令:
> cat("Hello",file="outfile.txt",sep="\n")
> cat("World",file="outfile.txt",append=TRUE)
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用R查看结果
> file.show("outfile.txt")
hello
world
Run Code Online (Sandbox Code Playgroud)
pet*_*ner 49
什么是简单的writeLines()?
txt <- "Hallo\nWorld"
writeLines(txt, "outfile.txt")
Run Code Online (Sandbox Code Playgroud)
要么
txt <- c("Hallo", "World")
writeLines(txt, "outfile.txt")
Run Code Online (Sandbox Code Playgroud)
小智 16
你可以在一个声明中做到这一点
cat("hello","world",file="output.txt",sep="\n",append=TRUE)
Run Code Online (Sandbox Code Playgroud)
Gwa*_*Kim 12
我建议:
writeLines(c("Hello","World"), "output.txt")
Run Code Online (Sandbox Code Playgroud)
它比目前接受的答案更短,更直接.没有必要这样做:
fileConn<-file("output.txt")
# writeLines command using fileConn connection
close(fileConn)
Run Code Online (Sandbox Code Playgroud)
因为文档writeLines()说:
如果
con是字符串,则函数调用file以获取在函数调用期间打开的文件连接.
# default settings for writeLines(): sep = "\n", useBytes = FALSE
# so: sep = "" would join all together e.g.
Run Code Online (Sandbox Code Playgroud)
如许多答案中所示,可以使用cat或writeLines实现将文本行写入 R 中的文件的简短方法。一些最短的可能性可能是:
cat("Hello\nWorld", file="output.txt")
writeLines("Hello\nWorld", "output.txt")
Run Code Online (Sandbox Code Playgroud)
如果您不喜欢“\n”,您还可以使用以下样式:
cat("Hello
World", file="output.txt")
writeLines("Hello
World", "output.txt")
Run Code Online (Sandbox Code Playgroud)
虽然在文件末尾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
Run Code Online (Sandbox Code Playgroud)
但主要的区别在于cat使用ř对象和writeLines一个字符向量作为参数。所以写出例如数字1:10需要为 writeLines 进行转换,而它可以像在 cat 中一样使用:
cat(1:10)
writeLines(as.character(1:10))
Run Code Online (Sandbox Code Playgroud)
并且cat可以接受许多对象,但writeLines只能接受一个向量:
cat("Hello", "World", sep="\n")
writeLines(c("Hello", "World"))
Run Code Online (Sandbox Code Playgroud)
带有管道的 tidyverse 版本和write_lines()来自 readr
library(tidyverse)
c('Hello', 'World') %>% write_lines( "output.txt")
Run Code Online (Sandbox Code Playgroud)
简单的怎么样write.table()?
text = c("Hello", "World")
write.table(text, file = "output.txt", col.names = F, row.names = F, quote = F)
Run Code Online (Sandbox Code Playgroud)
参数col.names = FALSE并row.names = FALSE确保排除txt中的行名和列名,并且参数quote = FALSE排除txt中每行开头和结尾的那些引号。要读回数据,您可以使用text = readLines("output.txt").