【发布时间】:2015-08-07 04:35:01
【问题描述】:
我一直无法在 Stack Overflow 上找到我的查询的解决方案。 This post is similar,但我的数据集略有不同——重要的是——不同(因为我的分组变量中有多个“时间”度量)。
随着时间的推移,我对不同地点的生物体进行了观察。这些站点进一步聚合成更大的区域,因此我希望最终有一个可以在 ddply 中调用的函数来汇总地理区域内每个时间段的数据集。但是,我无法获得所需的功能。
问题
如何循环遍历时间段并与前一个时间段进行比较,计算交叉点(即两个时间段内出现的“站点”数量)和每个时间段内出现的数量之和?
玩具数据集:
time = c(1,1,1,1,2,2,2,3,3,3,3,3)
site = c("A","B","C","D","A","B","C","A","B","C","D","E")
df <- as.data.frame(cbind(time,site))
df$time = as.numeric(df$time)
我的功能
dist2 <- function(df){
for(i in unique(df$time))
{
intersection <- length(which(df[df$time==i,"site"] %in% df[df$time==i- 1,"site"]))
both <- length(unique(df[df$time==i,"site"])) + length(unique(df[df$time==i-1,"site"]))
}
return(as.data.frame(cbind(time,intersection,both)))
}
dist2(df)
我得到了什么:
dist2(df) time intersection both 1 1 3 8 2 1 3 8 3 1 3 8 4 1 3 8 5 2 3 8 6 2 3 8 7 2 3 8 8 3 3 8 9 3 3 8 10 3 3 8 11 3 3 8 12 3 3 8
我期望(希望!)实现的目标:
time intersection both
1 1 NA 4
2 2 3 7
3 3 3 8
一旦我有了一个工作函数,我想在整个数据集上使用它和 ddply 来计算每个区域的这些值。
非常感谢您的任何指示、提示和建议!
我正在跑步:
R version 3.1.2 (2014-10-31)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
【问题讨论】: