【发布时间】:2020-06-15 19:11:11
【问题描述】:
我正在尝试生成空间有限随机游走的“假”数据集,即在每个时间步长,个人将随机移动任意距离 x 和 y,但这些值需要限制在我的竞技场(xlim和 ylim)——我并不特别关心当个人碰到边缘时会发生什么(反射或跟随墙壁),但他们不能越过边缘。
所有代码都会运行,并且函数“walker”在每次单独运行时都会给出新的和不同的值,但是当我通过 purrr::map 将其放入时,这些值只是为每个人重复。
我从几个来源拼凑起来,我相信它可以大大简化 - 最终,我希望 n.times 更大(最终目标是计算时间量*# 个人访问特定的方格),但第一步是让个人拥有不同的移动记录!
library(tidyverse)
n.times<-10
OUT <-data.frame(x.a = vector("numeric", n.times),y.a = vector("numeric", n.times))
walker <- function(n.times,
xlim=c(0,100),
ylim=c(0,30),
start=c(0,0),
stepsize=c(1,1)) {
## extract starting point
x <- start[1]
y <- start[2]
for (i in 1:n.times) {
repeat {
## pick jump sizes
xi <- stepsize[1]*sample(rnorm(n = n.times, mean = 0, sd = .5),1)
yi <- stepsize[2]*sample(rnorm(n = n.times, mean = 0, sd = .5),1)
## new candidate locations
newx <- x+xi
newy <- y+yi
## IF new locations are within bounds, then
## break out of the repeat{} loop (otherwise
## try again)
if (newx>xlim[1] && newx<xlim[2] &&
newy>ylim[1] && newy<ylim[2]) break
}
## set new location to candidate location
x <- newx
y <- newy
OUT[i,"x.a"] <-x
OUT[i, "y.a"] <-y
}
return(OUT)
}
#generate fake fish
fish<-data.frame(fish=as.character(letters[1:10]))
#apply walker to fake fish
fishmoves <- fish %>%
mutate(data= map(.,~walker(10))) %>%
unnest(data)
【问题讨论】: