riders994
riders994

Reputation: 1306

How to Export/Import Vectors in R?

I realize this is a pretty basic question, but I want to make sure I do it right, so I wanted to ask just to confirm. I have a vector in one project that I want to be able to use in another project, and I was wondering if there was a simple way to export the vector in a form that I can easily import it to another project.

The way that I figured out how to do it so far is to convert it to a df, then export the df as a csv, then import and unpack it to vector form, but that seems needlessly complicated. It's just a simple numeric vector.

Upvotes: 5

Views: 9417

Answers (2)

nathanesau
nathanesau

Reputation: 1721

I agree that saveRDS is a good way to go, but I also recommend the save and save.image functions, which I will demonstrate below.

# save.image 
x <- c(5,6,8)
y <- c(8,9,11)
save.image(file="~/vectors.Rdata") # saves all workspace objects

Or alternatively choose which objects you want to save

x <- c(5,6,8)
y <- c(8,9,11)
save(x, y, file="~/vectors.Rdata") # saves only the selected objects

One advantage to using .Rdata over .Rda (a minor one) is that you can click on the object in the file explorer (i.e. in windows) and it will be loaded into the R environment. This doesn't work with .Rda objects in say Rstudio on windows

Upvotes: 1

JasonAizkalns
JasonAizkalns

Reputation: 20463

There are a number of ways to read and write data/files in R. For reading, you may want to look at: read.table, read.csv, readLines, source, dget, load, unserialize, and readRDS. For writing, you will want to look write.table, writeLines, dump, dput, save, serialize, and saveRDS.

x <- 1:3
# [1] 1 2 3
save(x, file = "myvector.rda")

# Change x to prove a point.
x <- 4:6
x
# [1] 4 5 6

# Better yet, we could remove it entirely
rm(x)
x
# Error: object 'x' not found

# Now load what we saved to get us back to where we started.
load("myvector.rda")
x
# [1] 1 2 3

Alternatively, you can use saveRDS and readRDS -- best practice/convention is to use the .rds extension; note, however, that loading the object is slightly different as saveRDS does not save the object name:

saveRDS(x, file = "myvector_serialized.rds")
x <- readRDS("myvector_serialized.rds")

Finally, saveRDS is a lower-level function and therefore can only save one object a time. The traditional save approach allows you to save multiple objects at the same time, but can become a nightmare if you re-use the same names in different projects/files/scripts...

Upvotes: 7

Related Questions