Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use read.csv to read from a string value rather than a file in R?

I'm writing an R package where the R code talks to a Java application. The Java application outputs a CSV formatted string and I want the R code to be able to directly read the string and convert it into a data.frame.

like image 634
tommy chheng Avatar asked Oct 14 '10 18:10

tommy chheng


People also ask

What is the difference between read csv and Read_csv in R?

The read_csv function imports data into R as a tibble, while read. csv imports a regular old R data frame instead.

How do I read a CSV file in RStudio?

In RStudio, click on the Workspace tab, and then on “Import Dataset” -> “From text file”. A file browser will open up, locate the . csv file and click Open.

Which function would be used to read data from CSV file?

csv() Function. read. csv() function in R Language is used to read “comma separated value” files. It imports data in the form of a data frame.

What is the difference between read csv and read table?

csv() as well as the read. csv2() function are almost identical to the read. table() function, with the sole difference that they have the header and fill arguments set as TRUE by default. Tip: if you want to learn more about the arguments that you can use in the read.


2 Answers

Editing a 7-year old answer: By now, this is much simpler thanks to the text= argument which has been added to read.csv() and alike:

R> data <- read.csv(text="flim,flam + 1.2,2.2 + 77.1,3.14") R> data   flim flam 1  1.2 2.20 2 77.1 3.14 R>  

Yes, look at the help for textConnection() -- the very powerful notion in R is that essentially all readers (as e.g. read.table() and its variants) access these connection object which may be a file, or a remote URL, or a pipe coming in from another app, or ... some text as in your case.

The same trick is used for so-called here documents:

> lines <- " + flim,flam + 1.2,2.2 + 77.1,3.14 + " > con <- textConnection(lines) > data <- read.csv(con) > close(con) > data   flim flam 1  1.2 2.20 2 77.1 3.14 >  

Note that this is a simple way for building something but it is also costly due to the repeated parsing of all the data. There are other ways to get from Java to R, but this should get you going quickly. Efficiency comes next...

like image 171
Dirk Eddelbuettel Avatar answered Sep 22 '22 04:09

Dirk Eddelbuettel


Note that in now-current versions of R, you no longer need the textConnection(), it's possible to simply do this:

> states.str='"State","Abbreviation" + "Alabama","AL" + "Alaska","AK" + "Arizona","AZ" + "Arkansas","AR" + "California","CA"' > read.csv(text=states.str)        State Abbreviation 1    Alabama           AL 2     Alaska           AK 3    Arizona           AZ 4   Arkansas           AR 5 California           CA 
like image 36
Adam Bradley Avatar answered Sep 20 '22 04:09

Adam Bradley