Question

How can I save an MDS object for use in my next session of R? Because the metaMDS() function uses several random restarts it produces slightly different answers each time. I need the output to be consistent across several sessions of R. How can I achieve this? Thank you

Example of the type of ordination objects I am referring to:

data(dune)
sol <- metaMDS(dune)
sol
Was it helpful?

Solution

@csgillespie has shown how to make the results of metaMDS() reproducible. This setting of the pseudo-random number generator seed should be done all the time you use metaMDS() or any other function that uses the pseudo-random number generators in R or other software otherwise you won't be able to reproduce the results.

However, some metaMDS() fits can take a lot of computation time so serializing the result object to disk is an option. For that you want save() or saveRDS(). The difference between the two is that the former (save()) saves the entire object including its name. saveRDS() only serializes the object itself, not the name of the object in the current session.

load() can be used to restore the object saved by save(). It loads the object into the current session and will overwrite an object with the same name. readRDS() is used to load an object serialized by saveRDS().

require("vegan")
## The recommended way of running NMDS (Minchin 1987)
##
data(dune)
## Global NMDS using monoMDS
## set the seed
set.seed(1)
sol <- metaMDS(dune)

save(sol, file = "my_sol.rda")
ls()
rm(sol)
load("my_sol.rda")
ls()

saveRDS(sol, file = "my_sol.rds")
ls()
sol2 <- readRDS("my_sol.rds")
ls()
all.equal(sol, sol2)

Some of the pertinent output is:

>     save(sol, file = "my_sol.rda")
>     ls()
[1] "dune" "sol" 
>     rm(sol)
>     load("my_sol.rda")
>     ls()
[1] "dune" "sol" 
> 
>     saveRDS(sol, file = "my_sol.rds")
>     ls()
[1] "dune" "sol" 
>     sol2 <- readRDS("my_sol.rds")
>     ls()
[1] "dune" "sol"  "sol2"
>     all.equal(sol, sol2)
[1] TRUE

OTHER TIPS

When you want to use the same random numbers, you need to set the random number seed. For example,

##For some positive number
R> set.seed(1)
R> runif(1)
[1] 0.2655
R> set.seed(1)
R> runif(1)
[1] 0.2655

In your example, just use set.seed before the function call.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top