我正在尝试生成空间受限的随机游走的“伪”数据集,即,在每个时间步,个人将随机移动任意距离x和y,但是这些值必须限制在我的竞技场上(xlim和ylim)-我并不特别在意当个人碰到边缘时会发生什么(反射或跟随墙壁),但他们不能越过边缘。
所有代码都会运行,并且每次单独运行时,“ walker”函数都会提供新的值和不同的值,但是当我将其放入purrr :: map中时,每个人都会重复这些值。
[我从几个来源对此进行了梳理,我确信可以对其进行实质性的精简-最终,我希望n.n倍更大(最终目标是计算时间** #个人访问特定的网格正方形),但是第一步是使个人具有不同的运动记录!
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)
当您调用map时,它需要遍历与data.frame长度相同的数字。您使用了magrittr .
(在您的情况下将是整个data.frame)设置为1,因此将复制1值。
您可以做两件事:
res = tibble(fish) %>% mutate(data=map(fish,~walker(10)))
res$data[1:2]
[[1]]
x.a y.a
1 0.05691327 0.6609499
2 0.32432701 1.2174572
3 0.66515689 1.8964721
4 0.88173958 2.3758121
5 0.43781208 3.0526259
6 0.14187217 2.9216027
7 1.04768003 2.6636641
8 0.98632704 2.3824672
9 0.85341917 3.4224993
10 0.97703491 3.9261718
[[2]]
x.a y.a
1 0.4137715 0.3202513
2 0.3973849 0.2958951
3 0.9051333 0.4163088
4 0.6249996 0.4514562
5 1.1098010 0.1973155
6 1.1208103 0.6239122
7 1.2693395 1.1020321
8 0.9213216 1.4417686
9 1.0848714 0.5382004
10 0.8635316 0.4516631
不需要,但如果在以后的代码中需要按组进行操作,则很有用:
fish %>% group_by(fish) %>% mutate(data=map(.,~walker(10)))
顺便说一句,我会考虑将data.frame OUT
放在函数内部。