4

I don't want to write a csv into a file, but to get a string representation of the dataframe with a csv format (to send it over the network).

I'm using R.NET, if it helps to know.

0

3 Answers 3

7

If you are not limited to base functions, you may try readr::format_csv.

library(readr)
format_csv(iris[1:2, 1:3])
# [1] "Sepal.Length,Sepal.Width,Petal.Length\n5.1,3.5,1.4\n4.9,3.0,1.4\n"
Sign up to request clarification or add additional context in comments.

1 Comment

@RichScriven yeah, this answer seems to be the easiest; although it requires an additional package, using existing tools should be encouraged.
6

If you want a single string in csv format, you could capture the output from write.csv.

Let's use mtcars as an example:

paste(capture.output(write.csv(mtcars)), collapse = "\n")

This reads back into R fine with read.csv(text = ..., row.names = 1). You can make adjustments for the printing of row names and other attributes in write.csv.

2 Comments

It works but it appends a column with the rows' ids (e.i. 1,2,...,n)
@LayGonzález - You can adjust things like that in write.csv. For row names, it's row.names = FALSE to leave them off.
2

Alternatively:

write.csv(mtcars, textConnection("output", "w"), row.names=FALSE)

which will create the variable output in the global environment and store it in a character vector.

You can do

paste0(output, collapse="\n")

to make it one big character string, similar to Rich's answer (but paste0() is marginally faster).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.