如何在R中将纯文本文件作为单个字符串导入?我认为这可能会有一个非常简单的答案,但是当我今天尝试这个时,我发现我找不到这样做的功能.
例如,假设我有一个文件,foo.txt
其中包含我想要的文本.
我尝试过:
scan("foo.txt", what="character", sep=NULL)
Run Code Online (Sandbox Code Playgroud)
但这仍然返回了一个向量.我得到了一些工作:
paste(scan("foo.txt", what="character", sep=" "),collapse=" ")
Run Code Online (Sandbox Code Playgroud)
但这是一个非常丑陋的解决方案,也可能不稳定.
Tom*_*mmy 203
以下是来自@JoshuaUlrich的解决方案的变体,它使用正确的大小而不是硬编码的大小:
fileName <- 'foo.txt'
readChar(fileName, file.info(fileName)$size)
Run Code Online (Sandbox Code Playgroud)
请注意,readChar为您指定的字节数分配空间,因此readChar(fileName, .Machine$integer.max)
效果不佳...
Sha*_*ron 129
如果3年后有人还在看这个问题,Hadley Wickham的readr软件包有一个方便的read_file()
功能,可以为你做这个.
install.packages("readr") # you only need to do this one time on your system
library(readr)
mystring <- read_file("path/to/myfile.txt")
Run Code Online (Sandbox Code Playgroud)
Jos*_*ien 42
我会使用以下内容.它应该工作得很好,并且看起来并不丑,至少对我来说:
singleString <- paste(readLines("foo.txt"), collapse=" ")
Run Code Online (Sandbox Code Playgroud)
Jos*_*ich 12
怎么样:
string <- readChar("foo.txt",nchars=1e6)
Run Code Online (Sandbox Code Playgroud)
小智 8
太糟糕了,Sharon 的解决方案不能再使用了。我已将 Josh O'Brien 的解决方案与 asieira 的修改添加到我的 .Rprofile 文件中:
read.text = function(pathname)
{
return (paste(readLines(pathname), collapse="\n"))
}
Run Code Online (Sandbox Code Playgroud)
并使用它像这样:txt = read.text('path/to/my/file.txt')
。我无法复制bumpkin(14 年10 月28 日)的发现,并writeLines(txt)
显示了file.txt
. 另外,在write(txt, '/tmp/out')
命令后diff /tmp/out path/to/my/file.txt
报告没有差异。
readr包具有为您完成所有操作的功能.
install.packages("readr") # you only need to do this one time on your system
library(readr)
mystring <- read_file("path/to/myfile.txt")
Run Code Online (Sandbox Code Playgroud)
这将替换包stringr中的版本.