-2

The variables from inside the function are not getting stored in the global variables in R programming. Look at the code snippet:

install.packages('HMM')
library('HMM')

hmm_source <- function(){

  lamba_1 <- initHMM(c("s1","s2"), c("a","b","c"), c(1,0), matrix(c(.1,.6,.9,.4),nrow = 2,ncol = 2),matrix(c(.1,.4,.3,.2,.6,.4),nrow = 2,ncol = 3))

  lamba_2 <- initHMM(c("s1","s2"), c("a","b","c"), c(1,0), matrix(c(.4,.8,.6,.2),nrow = 2,ncol = 2),matrix(c(.5,.2,.4,.1,.1,.7),nrow = 2,ncol = 3))

  return(list(m1=lamba_1,m2=lamba_2))
}
source1_2 <- hmm_source()install.packages('HMM')
library('HMM')

hmm_source <- function(){

  lamba_1 <- initHMM(c("s1","s2"), c("a","b","c"), c(1,0), matrix(c(.1,.6,.9,.4),nrow = 2,ncol = 2),matrix(c(.1,.4,.3,.2,.6,.4),nrow = 2,ncol = 3))

  lamba_2 <- initHMM(c("s1","s2"), c("a","b","c"), c(1,0), matrix(c(.4,.8,.6,.2),nrow = 2,ncol = 2),matrix(c(.5,.2,.4,.1,.1,.7),nrow = 2,ncol = 3))

  return(list(m1=lamba_1,m2=lamba_2))
}
source1_2 <- hmm_source()

here my function returns the two hmm models but the variables lamba_1 and lamba_2 are not getting saved in global environment in R. I am working in RStudio, though i tried running the code in R shell too.. But it always give me the error : object lamba_1 not found. Any help ?

nrussell
  • 17,956
  • 4
  • 46
  • 60

1 Answers1

0

Objects created within functions are not stored to the global environment (by default, anyway). If you're returning lambda_1 and lambda_2, they will be elements of the returned object. They won't exist separately, but from the way you call the function, they should exist as source1_2$m1 and source1_2$m2.

Matt Tyers
  • 2,025
  • 1
  • 12
  • 21