Search code examples
rcsvfile-ioread.csv

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.


Solution

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