r - How to avoid loop when doing addition of row(n) to row(n-1) for random walk -
r - How to avoid loop when doing addition of row(n) to row(n-1) for random walk -
i simulating random walk starting coordinates(0,0). when loop works well:
require(ggplot2) n <- 1000 #number of walks # first solution, w/ loop... works slooow coord <- data.frame (x=0, y=0, step=0) #origin (i in 1:n){ dir <- sample(c("w", "e", "n", "s"), 1) #random direction step <- sample(1:4, 1) #how far go in each walk startx <- coord[nrow(coord), 1] starty <- coord[nrow(coord), 2] endx <- ifelse (dir=="w", startx-step, ifelse(dir=="e", startx+step, startx)) endy <- ifelse (dir=="n", starty+step, ifelse(dir=="s", starty-step, starty)) newcoord <- data.frame (x=endx, y=endy, step=step) coord <- rbind(coord, newcoord) } rw <- ggplot(coord, aes(x=x, y=y)) rw + geom_path() + ggtitle(paste(n, "walks")) + geom_point(aes(x=0, y =0), color="green", size=i(5)) + geom_point(aes(x=endx, y =endy), color="red", size=i(5))
however, n>10,000 gets slow, to avoid loop , utilize form of 'apply', can't figure out how add together values of coordinates rows n , n-1. please help, give thanks you.
# sec solution d <- data.frame(dir=sample(c("w", "e", "n", "s"), n, replace=t), step=sample(1:4, n, replace=t)) xy <- data.frame(x=0, y=0) x. <- data.frame(x=with(d, ifelse (dir=="w", -step, ifelse(dir=="e", step, 0)))) y. <- data.frame(y=with(d, ifelse (dir=="s", -step, ifelse(dir=="n", step, 0)))) x.y. <- cbind(x.,y.) xy <- rbind(xy, x.y.) head(xy) # ... stuck here
i think getting close. if read comments posted can create much faster. recommend not looking @ this:
n=10000 x.=sample(-4:4,n,rep=t) y.=sample(-4:4,n,rep=t) x=cumsum(x.) y=cumsum(y.) coord=data.frame(x,y)
then plot how did:
rw <- ggplot(coord, aes(x=x, y=y)) rw + geom_path() + ggtitle(paste(n, "walks")) + geom_point(aes(x=0, y =0), color="green", size=i(5)) + geom_point(aes(x=startx, y =starty), color="red", size=i(5))
update: plotting quite slow n bigger 10^5. maybe base of operations graphics faster.
update2: slow/fast joran's response.
r
Comments
Post a Comment