如何从字符向量解析 CSV 数据以提取数据框?

发布于 2024-09-10 06:42:45 字数 284 浏览 8 评论 0原文

R 中的 read.table 和 read.csv 函数用于解析包含分隔数据的文件或 URL 并生成 R 数据帧。但是,我已经有一个包含 CSV 分隔数据的字符向量(使用逗号和 \n 作为列和记录分隔符),因此我不需要从文件或 URL 中读取它。如何将此字符向量传递到 read.tableread.csvscan() 而不先将其写入磁盘上的文件并读回它?我意识到将其写入磁盘是可能的,但我正在寻找一种不需要这种不必要的往返并且可以直接从字符向量读取数据的解决方案。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

仅冇旳回忆 2024-09-17 06:42:45

您可以使用 textConnection() 将字符向量传递给 read.table()。示例:

x  <- "first,second\nthird,fourth\n"
x1 <- read.table(textConnection(x), sep = ",")
# x1
     V1     V2
1 first second
2 third fourth

R 邮件列表

2017 编辑

七年后,我可能会这样做:

read.table(text = x, sep = ",")

You can use textConnection() to pass the character vector to read.table(). An example:

x  <- "first,second\nthird,fourth\n"
x1 <- read.table(textConnection(x), sep = ",")
# x1
     V1     V2
1 first second
2 third fourth

Answer found in the R mailing list.

2017 EDIT

Seven years later, I'd probably do it like this:

read.table(text = x, sep = ",")
dawn曙光 2024-09-17 06:42:45

对 neilfws 答案的一个小补充。当提问者将原始数据放入问题中而不是提供数据框时,此包装函数非常适合帮助回答 stackoverflow 上的问题。

textToTable <- function(text, ...)
{
   dfr <- read.table(tc <- textConnection(text), ...)
   close(tc)
   dfr
}

随着使用,例如

textToTable("first,second\nthird,fourth\n", sep = ",")

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.

textToTable <- function(text, ...)
{
   dfr <- read.table(tc <- textConnection(text), ...)
   close(tc)
   dfr
}

With usage, e.g.

textToTable("first,second\nthird,fourth\n", sep = ",")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文