Amxx
Amxx

Reputation: 3070

Serialize structure

I'm new to R and I have basically no knowledge of data management in this language. I'm using the dynaTrees package to do some machine learning and I'd like to export the model to a file for further use.

The model is obtained by calling the dynaTrees function:

model <- dynaTrees(
    as.matrix(training.data[,-1]),
    as.matrix(training.data[, 1]),
    R=10
)

I then want to export this model object so it can be loaded in another script later on. I tried the simple:

write(model, file="model.dat")

but that doesn't work (type list not supported).

Is there a generic way (or a dedicated package) in R to export complex data structure to file?

Upvotes: 1

Views: 69

Answers (1)

Thomas
Thomas

Reputation: 44535

You probably want saveRDS (see ? saveRDS for details). Example:

saveRDS(model, file = "model.Rds")

This saves a single R object to file so that you can restore it later (using readRDS). save is an alternative that is designed for saving multiple R objects (or an entire workspace), which can be accessed later using load.

Your intuition was to use the write function, which is actually a rarely used tool for writing a matrix to a text representation. Here's an example:

write(as.matrix(warpbreaks[1:3,]), file = stdout())
# 26
# 30
# 54
# A
# A
# A
# L
# L
# L

Upvotes: 1

Related Questions