0

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

Prune
  • 76,765
  • 14
  • 60
  • 81
  • How about you make a matrix with a very large number of rows, do the calculations, and the drop unused rows when done? – DanY Dec 04 '20 at 04:21
  • Deleted inapplicable tags. Appending to a list is not a problem in Python. – Prune Dec 04 '20 at 04:27
  • You don't need a matrix that is capable of displying all the "walking", You can just use a two column matrix or dataframe with x and y positions and then iterate over the rows, incrementing or decrementing by 1 unit for each successive time(row). The test for falling off the cliff is simply that the x or y position exceeds a set value (depending on where the cliff is located). – IRTFM Dec 04 '20 at 05:03

0 Answers0