将文本文件导入为单个字符串

如何在R中将纯文本文件作为单个字符串导入?我认为这可能会有一个非常简单的答案,但是当我今天尝试此操作时,我发现找不到用于执行此操作的函数。


例如,假设我有一个文件,foo.txt其中包含我想文本的内容。


我尝试了:


scan("foo.txt", what="character", sep=NULL)

但这仍然返回一个向量。我得到它与一些工作:


paste(scan("foo.txt", what="character", sep=" "),collapse=" ")

但这是一个丑陋的解决方案,也可能不稳定。


幕布斯6054654
浏览 645回答 3
3回答

MYYA

如果三年后仍然有人在看这个问题,Hadley Wickham的阅读器程序包read_file()将为您提供方便的功能。install.packages("readr") # you only need to do this one time on your systemlibrary(readr)mystring <- read_file("path/to/myfile.txt")

宝慕林4294392

太糟糕了,无法再使用Sharon的解决方案。我已经将Josh O'Brien的解决方案以及对asieira的修改添加到了.Rprofile文件中:read.text = function(pathname){&nbsp; &nbsp; return (paste(readLines(pathname), collapse="\n"))}并像这样使用它:txt = read.text('path/to/my/file.txt')。我无法复制布金(10月28日)的发现,并writeLines(txt)显示的内容file.txt。另外,write(txt, '/tmp/out')命令后diff /tmp/out path/to/my/file.txt报告无差异。
打开App,查看更多内容
随时随地看视频慕课网APP