如何使用多字节分隔符将文本文件读入 GNU R?
我可以使用 read.csv 或 read.csv2 将数据读取到 R 中。但我遇到的问题是我的分隔符是多字节字符串而不是单个字符。我该如何处理这个问题?
I can use read.csv or read.csv2 to read data into R. But the issue I encountered is that my separator is a multiple-byte string instead of a single character. How can I deal with this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
提供示例数据会有帮助。但是,您也许可以根据您的需要调整以下内容。
我创建了一个示例数据文件,它只是一个包含以下内容的文本文件:
我将其另存为“test.csv”。分隔符是“sep”字符串。我认为
read.csv()
使用scan()
,它只接受sep
的单个字符。要解决此问题,请考虑以下事项:readLines()
仅读取其中的行。gsub
用多字符分隔字符串替换单个' ' 或任何对您的数据方便的内容。然后
textConnection()
和read.data()
方便地读回所有内容。对于较小的数据集,这应该没问题。如果您有非常大的数据,请考虑使用 AWK 之类的预处理来替换多字符分隔字符串。以上内容来自 http://tolstoy.newcastle.edu .au/R/e4/help/08/04/9296.html 。更新
关于您的评论,如果您的数据中有空格,请使用不同的替换分隔符。考虑将
test.csv
更改为:然后,使用以下函数:
尝试:
在这里,用制表符 (
\t
) 替换原始分隔符。as.is
被传递给read.table()
以防止字符串被读入 is 因子,但这是你的决定。如果数据中有更复杂的空白,您可能会发现read.table()
中的quote
参数很有帮助,或者使用 AWK、perl 等进行预处理。与 crippledlambda 的
strsplit()
类似的东西很可能与中等大小的数据等效。如果性能成为问题,请尝试两者,看看哪种适合您。Providing example data would help. However, you might be able to adapt the following to your needs.
I created an example data file, which is a just a text file containing the following:
I saved it as 'test.csv'. The separation character is the 'sep' string. I think
read.csv()
usesscan()
, which only accepts a single character forsep
. To get around it, consider the following:readLines()
just reads the lines in.gsub
substitutes the multi-character seperation string for a single' '
, or whatever is convenient for your data. ThentextConnection()
andread.data()
reads everything back in conveniently. For smaller datasets, this should be fine. If you have very large data, consider preprocessing with something like AWK to substitute the multi-character separation string. The above is from http://tolstoy.newcastle.edu.au/R/e4/help/08/04/9296.html .Update
Regarding your comment, if you have spaces in your data, use a different replacement separator. Consider changing
test.csv
to :Then, with the following function:
Try:
Here, you replace the original separator with tabs (
\t
). Theas.is
is passed toread.table()
to prevent strings being read in is factors, but that's your call. If you have more complicated white space within your data, you might find thequote
argument inread.table()
helpful, or pre-process with AWK, perl, etc.Something similar with crippledlambda's
strsplit()
is most likely equivalent for moderately sized data. If performance becomes an issue, try both and see which works for you.在这种情况下,您可以将
textConnection(txt)
替换为您的文件名,但本质上您可以围绕strsplit
构建代码或函数。在这里,我假设您有一个标题行,但您当然可以定义一个header
参数,并根据以下函数概括数据框的创建:In this case you can replace
textConnection(txt)
with your file name, but essentially you can build a code or function aroundstrsplit
. Here I'm assuming you have a header line, but you can of course give define aheader
argument and generalize the creation of your data frame based on the function below: