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

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


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     V21 first second2 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 = ",")


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 = ",")