pedro
pedro

Reputation: 463

How to reuse a variable from one R script to another one?

I have a variable combs (which is a matrix with 10 rows x 2 columns) in my 1_script.R . I need to reuse this variable into my 2_script.R . I tried to source() the first script but that loads all the script, whereas I just need the variable combs .

Any help?

Upvotes: 1

Views: 1516

Answers (1)

Andrew Brēza
Andrew Brēza

Reputation: 8327

There are a few ways to do this. If you have a model that takes a long time to train and you want to use it in another place, you can use R's RDS file format to save the model as a file and load it in the future without having to train it again.

# Create a model and save it to a variable
model_lm <- lm(mpg ~ ., data = mtcars)

# Store the model as an RDS file
saveRDS(object = model_lm, file = "model_lm.rds")

# Load the model from file
model_lm2 <- readRDS("model_lm.rds")

# Use the model however you want
predict(object = model_lm2, newdata = mtcars)

Upvotes: 1

Related Questions