如何从字符向量解析CSV数据以提取数据框架? [英] How can I parse CSV data from a character vector to extract a data frame?

查看:143
本文介绍了如何从字符向量解析CSV数据以提取数据框架?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

R中的read.table和read.csv函数用于解析包含分隔数据的文件或URL,并生成R数据框。但是,我已经有一个包含CSV分隔数据的字符向量(使用逗号和\\\
作为列和记录分隔符),因此我不需要从文件或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.

推荐答案

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

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

R邮寄清单

这篇关于如何从字符向量解析CSV数据以提取数据框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆