我已经产生了一系列的个人随机行走,它们绕着一个有界的竞技场移动(data.frame fishmoves)。在这个领域内,有一些有趣的网格正方形(data.frame蚂蚁,盒子的x和y坐标)。我想过滤鱼群,使其仅包含感兴趣的网格正方形内的点。然后,我想计算个人的数量和每个人在每个框中花费的时间步长。
我在过滤上遇到障碍。我正在使用purr :: map2从蚂蚁传递过滤条件,但是当我调用所有四个参数时却无法正常工作,而是返回null。我确保(data.frame tester)可以找到实际值,因此一定是我在调用中做错了。
这阻止了我进入下一步,按蚂蚁分割,按时间步长和个体进行汇总。任何帮助将不胜感激!
library(tidyverse)
n.times<-1000
OUT <-data.frame(time=vector("numeric", n.times), x.a = vector("numeric", n.times),y.a = vector("numeric", n.times))
walker <- function(n.times,
xlim=c(0,40),
ylim=c(0,20),
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,"time"]<-i
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(fish,~walker(n.times))) %>%
unnest(data)
#ants <- data.frame(ant=c("a", "b"),x.min=seq(from=2, to = 38, by= 4)),x.max=c(1,4),y.min=c(0,2), y.max=c(1,3))
ants <- data.frame(ant=LETTERS[1:16]) %>%
bind_cols(x.min=c(seq(from=4, to = 32, by= 4),seq(from=4, to = 32, by= 4)),
y.min=c(rep(4,each=8),rep(12,each=8))) %>%
mutate(x.max=x.min+2,
y.max=y.min+2) %>%
group_by(ant)
#filter fishmoves based on the filter parameters - works separately for both x and y
ant_fish1 <- map2(ants$x.min, ants$x.max, ~ fishmoves %>%
filter(between(x.a, ..1[1], ..2[1])) )
ant_fish2 <- map2(ants$y.min, ants$y.max, ~ fishmoves %>%
filter(between(y.a, ..1[1], ..2[1])) )
#test to demonstrate that there are individuals that meet the joint criteria
tester <- fishmoves %>% filter (between(x.a, ants$x.min[1], ants$x.max[1]) & between(y.a, ants$y.min[1], ants$y.max[1]))
#filter returns null
ant_fish3 <- map2(ants$x.min, ants$x.max, ants$y.min, ants$y.max, ~ fishmoves %>%
filter(between(x.a, ..1[1], ..2[1]) & between(y.a, ..3[1], ..4[1])) )
#conceptual approach? does not work...
ant_fish <- ants %>% nest(ant_loc = c(x.min, x.max, y.min, y.max)) %>%
map2(ants$x.min, ants$x.max, ants$y.min, ants$y.max, ~ fishmoves %>%
filter(between(x.a, ..1[1], ..2[1]) & between(y.a, ..3[1], ..4[1])) ) %>%
group_by(fish) %>%
summarise(counts=n())
问题是您不能像这样使用map2。 map2中的2表示您用来映射的函数必须接受2个(并且只有2个)参数,但是您要传递4个。执行所需功能的映射函数称为pmap。