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

Asked

Viewed 1,242 times

1

I have a list object, similar to the one below:

 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 _ _ _ ?

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

3

You can also save in format .rds, he is more flexible than the .rda in the sense that you can upload the list with the 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")

2

Besides the other alternatives, I also like to save in a file .json. This file format has become standard in data sharing 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 archive x.json 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, it is possible to read the file like this:

x <- fromJSON(txt = "x.json")

2

Using the package’s write.list() function erer.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.