Lay González
Lay González

Reputation: 2985

How can a data frame be transformed into a string with a csv format on R?

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.

Upvotes: 4

Views: 411

Answers (3)

hrbrmstr
hrbrmstr

Reputation: 78832

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

Upvotes: 2

Rich Scriven
Rich Scriven

Reputation: 99371

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.

Upvotes: 6

Henrik
Henrik

Reputation: 67828

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"

Upvotes: 7

Related Questions