我正在模拟从坐标(0,0)开始的随机游走。当我使用循环执行此操作时,效果很好:
require(ggplot2)
n <- 1000 #number of walks
# first solution, w/ loop... works but is SLOOOW
coord <- data.frame (x=0, y=0, step=0) #origin
for (i in 1:n){
dir <- sample(c("w", "e", "n", "s"), 1) #random direction
step <- sample(1:4, 1) #how far to 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))
但是,当 n>10,000 时,它会变得非常慢,因此希望避免循环并使用某种形式的“应用”,但不知道如何添加第 n 行和第 n-1 行的坐标值。请帮忙,谢谢。
# second 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