0

I have made an LDA model in R using MASS.

set.seed(1)  # for reproducibility
library(MASS)
mydata <- data.frame(Segments=sample(1:4, 15, replace=TRUE),
                             var1=sample(1:7, 15, replace=TRUE),
                             var2=sample(1:7, 15, replace=TRUE),
                             var3=sample(1:6, 15, replace=TRUE),
                             var4=sample(1:2, 15, replace=TRUE))
mymodel <- lda(Segments~., data=mydata)

I know that if I want to run this model on different data, I can use predict, e.g.

set.seed(10)
mydata2 <- data.frame(Segments=sample(1:4, 15, replace=TRUE),
                                 var1=sample(1:7, 15, replace=TRUE),
                                 var2=sample(1:7, 15, replace=TRUE),
                                 var3=sample(1:6, 15, replace=TRUE),
                                 var4=sample(1:2, 15, replace=TRUE))
newmodel <- predict(mymodel, newdata = mydata2)
newmodel$class # View predicted groups

I would like to make the model available for other people to use on their own data. However, I don't want to share my data that I used to build the model. Is there some way that I can export this model in a sharable way? And how would other people go about importing it?

For example, is it possible to export the model as a csv and for someone else to import it in a way that R recognises it as a model? The idea is that they will be able to use predict with their own data and my model.

zephryl
  • 14,633
  • 3
  • 11
  • 30
thestral
  • 491
  • 1
  • 4
  • 16
  • You could s`save` the model as an RData object and then `load` it back into R. Though one stick can be able to look into the structure of the model and see the data used to build it. This is almost similar to `pickle` – Onyambu Feb 28 '23 at 05:31
  • Thanks! I didn't quite get there with save and load (it just saved the name of my model as a character string, rather than saving the model), but in googling `save` I came across this post: https://stackoverflow.com/questions/14761496/saving-and-loading-a-model-in-r That had exactly what I needed! saveRDS and readRDS – thestral Feb 28 '23 at 06:16
  • Yes you could use `.Rds` or `.Rdata` both works fine – Onyambu Feb 28 '23 at 06:54

1 Answers1

0

Found the answer here: Saving and loading a model in R Thanks onyambu for pointing me in the right direction, and thanks lbcommer for the answer in the linked post. Here is the solution:

saveRDS(mymodel, "model.rds")
my_model <- readRDS("model.rds")
thestral
  • 491
  • 1
  • 4
  • 16