Writing an RDA to CSV in R

一世执手 提交于 2019-12-24 05:31:15

问题


I'm trying to write a script to load an RDA by filename and write an equivalent file out as CSV.

It's almost there (with the loading and writing) however the output CSV contains the vector of strings returned by load(), rather than the data frame referenced by load...

$ cat convert.r
#!/usr/bin/env Rscript

argv <- commandArgs(TRUE)
inFile <- toString(argv[1])
print(inFile)

outFile <- gsub(".rda$", ".csv", inFile)
print(outFile)

inData <- load(inFile)
write.csv(inData, file=outFile)

This is the command + output...

/convert.r data.rda
[1] "data.rda"
[1] "data.csv"
[1] "table.data"

So you can see its picking up the input filename from the arguments, it's creating the right output filename, but the inData is a reference to the global object called table.data. When write.csv runs, it just contains this:

$ cat data.csv
"","x"
"1","table.data"

How do I make write.csv pick up the data-frame from the rda file? I understand there is a current risk if the RDA contains more than one frame - maybe it should loop over them and do file-frame.csv?!


回答1:


Clearly the best way to solve a problem yourself is to publically ask a question.

The answer is: get()

inData <- load(inFile)
write.csv(get(inData), file=outFile)

(Answer found on https://stackoverflow.com/a/6316461/224707 by greg-snow)



来源:https://stackoverflow.com/questions/32398127/writing-an-rda-to-csv-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!