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

Solution 1:

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...

Solution 2:

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