如何从字符向量解析 CSV 数据以提取数据框?
R 中的 read.table 和 read.csv 函数用于解析包含分隔数据的文件或 URL 并生成 R 数据帧。但是,我已经有一个包含 CSV 分隔数据的字符向量(使用逗号和 \n 作为列和记录分隔符),因此我不需要从文件或 URL 中读取它。如何将此字符向量传递到 read.table
、read.csv
或 scan()
而不先将其写入磁盘上的文件并读回它?我意识到将其写入磁盘是可能的,但我正在寻找一种不需要这种不必要的往返并且可以直接从字符向量读取数据的解决方案。
The read.table and read.csv functions in R are used to parse a file or URL containing delimited data and produce an R data frame. However, I already have a character vector that contains the CSV delimited data (using comma and \n as column and record delimiters), so I don't need to read it from a file or URL. How can I pass this character vector into read.table
, read.csv
, or scan()
without writing it to a file on disk first and reading it back in? I realize that writing it to disk is possible, but I am looking for a solution that does not require this needless roundtrip and can read data from the character vector directly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 textConnection() 将字符向量传递给 read.table()。示例:
在 R 邮件列表。
2017 编辑
七年后,我可能会这样做:
You can use textConnection() to pass the character vector to read.table(). An example:
Answer found in the R mailing list.
2017 EDIT
Seven years later, I'd probably do it like this:
对 neilfws 答案的一个小补充。当提问者将原始数据放入问题中而不是提供数据框时,此包装函数非常适合帮助回答 stackoverflow 上的问题。
随着使用,例如
A minor addendum to neilfws's answer. This wrapper function is great for helping answer questions on stackoverflow when the questioner has placed raw data in their question rather than providing a data frame.
With usage, e.g.