0

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
Elizabeth
  • 6,391
  • 17
  • 62
  • 90

2 Answers2

2

@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
Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
1

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.

csgillespie
  • 59,189
  • 14
  • 150
  • 185
  • So even if I close down R and do no save my workspace the next time I open my .R script and run the script will it still use the same random numbers. Also, there are several random restarts each time you run metaMDS so with set.seed ensure that each random restart within the function is the same? – Elizabeth Sep 19 '12 at 17:00
  • @Elizabeth: You seem to be under the misconception that computers generate random numbers. The is a famous quotation by a famous mathematician, possibly von Neumann, that says persons attempting to use computers for that purpose are in "a state of numerical sin'. – IRTFM Sep 19 '12 at 17:46