1

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?

VPailler
  • 185
  • 1
  • 10
  • The 1_script.R and 2_script do not store any variable. R has an environment which you working with (and where your variables are stored). The scripts are just text which you pass to that environment, so you do not need to source the second script to use the data frame you have generated with the first script. – Freakazoid Apr 29 '19 at 12:39
  • Save the object in your first script, then load the object in the second script. Read about saving objects [here](https://stackoverflow.com/q/21370132/680068). – zx8754 Apr 29 '19 at 12:42
  • I know what you mean. But when I execute the 2_script.R , I get an error `Error in nrow(combs) : object 'combs' not found ` – VPailler Apr 29 '19 at 12:45

1 Answers1

1

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)
Andrew Brēza
  • 7,705
  • 3
  • 34
  • 40