[英]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). 我不想将csv写入文件,而是使用csv格式获取数据帧的字符串表示(通过网络发送)。
I'm using R.NET, if it helps to know. 我正在使用R.NET,如果它有助于了解。
If you are not limited to base
functions, you may try readr::format_csv
. 如果您不限于
base
功能,可以尝试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"
If you want a single string in csv format, you could capture the output from write.csv
. 如果你想要一个csv格式的单个字符串,你可以从
write.csv
捕获输出。
Let's use mtcars
as an example: 我们以
mtcars
为例:
paste(capture.output(write.csv(mtcars)), collapse = "\n")
This reads back into R fine with read.csv(text = ..., row.names = 1)
. 这用
read.csv(text = ..., row.names = 1)
读回R fine。 You can make adjustments for the printing of row names and other attributes in write.csv
. 您可以在
write.csv
调整行名称和其他属性的write.csv
。
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. 这将在全局环境中创建变量
output
并将其存储在字符向量中。
You can do 你可以做
paste0(output, collapse="\n")
to make it one big character string, similar to Rich's answer (but paste0()
is marginally faster). 使它成为一个大字符串,类似于Rich的答案(但是
paste0()
快一些)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.