Need to create a matrix with an unspecified amount of rows so that a for loop can write values to the matrix

57 Views Asked by At

I am modeling the drunkards walk in 2D ( a variation of a random walk which ends if the drunk man falls off a cliff). I need to know if there is any way to create the matrix "walk" without specifying the number of rows initially. I was thinking that there might be a way to do this using a data frame but could not figure it out. Someone please help. Code is below

#specifying parameters
nSims<- 1000

#defining walk as vector of unspecified length
walk<- matrix(NA, nrow= 999999, ncol=2)
rstep<- matrix(c(1, 0, -1, 0, 0, 1, 0, -1), nrow=4, ncol=2, byrow=TRUE)

#setting counters
nReturns<- 0
nFalls<- 0
nSuccesses<- 0
totalsteps<- 0
#setting seed number
#set.seed(77077)

#simulating trajectories until hitting N or 0

for (i in 1:nSims) {
walk[1,]<- c(0,0)
k<- 2
nsteps<- 0
repeat {
  walk[k,]<- walk[k-1,]+rstep[sample(1:4, size=1),]
  nSteps = nSteps + 1
  if(nSteps==9999){
    nSuccesses = nSuccesses + 1
    break
  }
  else if (walk[k,1]==30) { 
    nFalls = nFalls + 1
    break
  }
  else if(walk[k,1]==0 & walk[k,2]==0) {
    nReturns = nReturns + 1
  }
  k<- k+1
  totalsteps = totalsteps + 1
  }

} #nFalls + nSuccesses should add up to totalsteps nFalls nReturns nSuccesses

0

There are 0 best solutions below