1

I am trying to run a simulation of a probability matrix with 5 states.

N<-10 #for 10 simulations
state<-simulat(P,N,1) #P is a matrix defined earlier in my code

for(i in 1:N)
    {
        if (state[i]=='0')
        {
            time[i]<-rexp(1,Mu)
        }
        if (state[i]=='1' || state[i]=='2' || state[i]=='3')
        {
            time[i]<-rexp(1,(Mu+Lamda))
        }
        if (state[i]=='4')
        {
            time[i]<-rexp(1,Lamda)
        }
    }
Error in time[i] <- rexp(1, Mu) : 
  object of type 'closure' is not subsettable

Is this an issue with formatting or am I defining my state[i] incorrectly? I have tried switching my [] to (), but then it gives me an error that says it could not find function 'state', even though I had just defined it above. Any help is appreciated.

Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
user2175485
  • 21
  • 1
  • 1
  • 4
  • 3
    There's a function called `time()`. Unless you've initialized a vector called time (e.g. `time <- rep(NA,N)`) R will try to subset the function. Anytime you see "object of type 'closure'" in an error, R just means "a function". (And probably best not to name the vector time, anyway, just to avoid confusion.) – joran Mar 15 '13 at 20:40
  • @joran is right, but even if you change `time` to, say, `tiempo`, you will have an error (a different one, though). The conclusion is that you need to create a vector `time` beforehand : `time <- numeric(N)`. Or, better `tiempo <- numeric(N)`, and use `tiempo[i]` instead of `time[i]`. – Elvis Mar 15 '13 at 20:47
  • Thank you, once I switched time() to tiempo() and added tiempo as a vector it worked. I didn't realize that since I was writing the code in the script editor in R instead of in notepad++ where it colors words already stored as a function. – user2175485 Mar 15 '13 at 21:47
  • There are enough functions in so many packages that this happens to everyone eventually, syntax highlighting or not. The key (for me) was knowing what "object of type 'closure'" means. – joran Mar 15 '13 at 21:51

1 Answers1

1

In addition to my comment, here is another solution:

tiempo <- ifelse(state == '0', rexp(N,Mu), 
                 ifelse(state == '4', rexp(N,Lambda), rexp(N, Mu+Lambda)))

Avoiding the loop is likely to shorten the execution time.

Elvis
  • 548
  • 2
  • 14