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.
The read_csv function imports data into R as a tibble, while read. csv imports a regular old R data frame instead.
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.
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.
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.
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...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With