How can I save a list or export an object of type list in R?

1

I have an object of type list, similar to this that follows:

 x<- list(cod = 1:10, taxa = exp(-3:3), logico = c(TRUE,FALSE,FALSE,TRUE))

What is the best way to store this object in * .R, * .csv or _ _ _?

    
asked by anonymous 17.11.2015 / 03:02

4 answers

3

Alternatives using R's own functions are:

Save as binary file, which takes up less space, but can only be opened in R.

save(x, file = "arquivo.RData")
save.image(file = "todoWorkspace.RData") # Salva todo workspace

Save as text, but also only readable in R, using dput :

write(dput(x), file = "arquivo.txt")
    
17.11.2015 / 04:44
3

You can also save in .rds format, it is more flexible than .rda in the sense that you can load the list with whatever name you find most appropriate.

# salva lista x no arquivo x.rds
saveRDS(x, "x.rds")
# le lista mas com nome y agora
y <- readRDS("x.rds")
    
17.11.2015 / 12:35
2

Using the write.list () function of the erer package.

x<- list(cod = 1:10, taxa = exp(-3:3), logico = c(TRUE,FALSE,FALSE,TRUE))

library(erer)
write.list(x,file="caminhodoarquivo.R")

or

write.list(x,file="caminhodoarquivo.csv")
    
17.11.2015 / 03:02
2

In addition to the other alternatives, I also like to save to a .json file. This file format has become standard in sharing data in list format.

In R, it's easy to save like this:

x<- list(cod = 1:10, taxa = exp(-3:3), logico = c(TRUE,FALSE,FALSE,TRUE))
library(jsonlite)
write(toJSON(x), file = "x.json")

The x.json file is actually a text file with the following content:

{
  "cod": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  "taxa": [0.0498, 0.1353, 0.3679, 1, 2.7183, 7.3891, 20.0855],
  "logico": [true, false, false, true]
} 

Later, you can read the file like this:

x <- fromJSON(txt = "x.json")
    
18.11.2015 / 00:40