在R中向文件写入文本行

446
在 R 编程语言中,我如何编写文本行,例如以下两行?
Hello
World

如何将输出保存到名为"output.txt"的文件中?

13个回答

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

8
马克 - 如果我有几个线程,它们都要往同一个文件里添加行,怎么办?(问题在于您不能对一个文件进行多次连接,如果我没记错的话) 谢谢。 - Tal Galili
12
@Tal,这是一个很好的问题,你应该将其作为一个新的、独立的问题发布,这样它就能得到关注。这里有比我更有知识的R程序员! - Mark
13
请注意,这需要文件“output.txt”已经存在。如果不存在,则必须首先创建它,例如使用 'file.create("output.txt")'。 - Eike P.
24
@jhin,我不确定这是真的。如果使用RStudio 0.98和R版本3.1.0,则会自动创建该文件(如果不存在)。 - JHowIX
6
writeLines()函数的选项大约比sink()cat()组合快10倍。 - rafa.pereira
显示剩余8条评论

188

实际上,你可以使用sink()来实现:

sink("outfile.txt")
cat("hello")
cat("\n")
cat("world")
sink()

因此做:

file.show("outfile.txt")
# hello
# world

sink()在Databricks上无法正常工作,请小心使用。 您可以将所有这些放在一个函数中,并像这样调用该函数:capture.output(函数调用, 文件名) - abdkumar
感谢@aL3xa。但请记住,这段代码有效地将控制台中的所有内容(包括执行的代码)都写入了文件。 - don_Gunner94

150

我会像这个例子一样使用cat()命令:

> cat("Hello",file="outfile.txt",sep="\n")
> cat("World",file="outfile.txt",append=TRUE)

然后,您可以使用以下代码在 R 中查看结果:

> file.show("outfile.txt")
hello
world

12
它不断地打开和关闭一个文件。这种方法可能效率低下。 - mlt

86

那么,简单地使用 writeLines() 有什么问题吗?

txt <- "Hallo\nWorld"
writeLines(txt, "outfile.txt")
或者
txt <- c("Hallo", "World")
writeLines(txt, "outfile.txt")

6
很好展示输入不一定要是一系列向量。 - tim
2
@tim 实际上,"Hallo\nWorld" 是字符类型的长度为1的向量。只需尝试 txt <- "Hallo\nWorld"; is.character(txt) && length(txt) == 1 && is.vector(txt) 即可。 - zero323
这对我只有在writeLines(txt, con="outfile.txt")的情况下有效。 - Palec
1
不需要命名参数,只要在第二个参数中提供有效的文件名,就应该可以正常工作。 - petermeissner
@petermeissner `> coefficients<-summary(model)
writeLines(coefficients, "coefficients") writeLines(coefficients, "coefficients")出现错误:无效的“text”参数`
- alhelal
你不能简单地将任何内容写入文件(“无效的'text'参数”)。它必须是字符向量:例如: library(magrittr); data.frame(y=1:10, x=rnorm(10)) %>% lm() %>% summary() %>% capture.output() %>% writeLines("coef.txt"); readLines("coef.txt") - petermeissner

26

我建议:

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.

值得注意的是,writeLines 只能打印字符向量。 - macieksk

24

你可以用一条语句完成这个操作

cat("hello","world",file="output.txt",sep="\n",append=TRUE)

21
在R中,可以通过catwriteLines来实现将文本行写入文件的简短方法,正如许多答案中已经展示的那样。其中一些最短的可能性可能是:
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))

而且 cat 可以接受 多个 对象,但 writeLines 只能接受 一个 向量:

cat("Hello", "World", sep="\n")
writeLines(c("Hello", "World"))

追加到现有文件使用cat更容易。但是这个选项会为每个事务永久打开和关闭文件。因此,对于许多追加写入,连接可能更可取。命令file中的a代表以文本模式追加打开。另一个选项是w,表示以文本模式写入打开以创建一个新文件进行写入。
cat("Hello\n", file="output.txt")
cat("World", file="output.txt", append=TRUE)

cat("Hello\n", file="output.txt")
CON <- file("output.txt", "a")
cat("World", file=CON)
close(CON)

writeLines("Hello", "output.txt")
CON <- file("output.txt", "a")
writeLines("World", CON)
close(CON)

另一方面,writeLinescat更快速。
bench::mark(check=FALSE,
writeLines(c("Hello", "World")),
cat("Hello", "World", sep="\n"),
writeLines(c("Hello", "World"), sep=" "),
cat(c("Hello", "World")),
cat("Hello", "World") )
#  expression                                      min   median `itr/sec` mem_a…¹
#  <bch:expr>                                 <bch:tm> <bch:tm>     <dbl> <bch:b>
#1 writeLines(c("Hello", "World"))              2.27µs   4.77µs   163878.      0B
#2 cat("Hello", "World", sep = "\n")            3.83µs   8.51µs   118708.      0B
#3 writeLines(c("Hello", "World"), sep = " ")   1.99µs   4.25µs   235944.      0B
#4 cat(c("Hello", "World"))                      4.1µs   6.84µs   141797.      0B
#5 cat("Hello", "World")                        3.46µs   7.06µs   129865.      0B

11

使用管道和来自readr的write_lines()的tidyverse版本

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

5

那么使用简单的 write.table() 会怎样呢?

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

参数col.names = FALSErow.names = FALSE确保在文本中排除行和列名,参数quote = FALSE则排除了文本中每行开头和结尾的引号。 要将数据读回来,您可以使用 text = readLines("output.txt")

2
为了完整掌握此技术,您可以使用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"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接