Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse CSV data from a character vector to extract a data frame?

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.

like image 985
MattJ Avatar asked Jul 16 '10 00:07

MattJ


People also ask

How do I read a column from a csv file in R?

Method 1: Using read. table() function. In this method of only importing the selected columns of the CSV file data, the user needs to call the read. table() function, which is an in-built function of R programming language, and then passes the selected column in its arguments to import particular columns from the data.

What's the difference between read_csv () and read_csv2 ()?

read_csv() reads comma delimited files, read_csv2() reads semicolon separated files (common in countries where , is used as the decimal place), read_tsv() reads tab delimited files, and read_delim() reads in files with any delimiter.


1 Answers

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 = ",")
like image 95
neilfws Avatar answered Sep 26 '22 21:09

neilfws