【发布时间】:2018-11-19 05:00:13
【问题描述】:
我有一个示例 data.frame,“事件”,它在一次潜水中发生了多个猎物捕获。根据捕获列,我使用了“处理”这个词来计算每次潜水的捕获次数。
但是,在某些情况下,我在一次潜水中有多种猎物类型。如何计算基于物种捕获的猎物数量(即单次潜水捕获了多少 fish.a 和多少 fish.b)?
任何建议将不胜感激。
events <- data.frame(Prey_present =c("fish.a", "fish.a","", "fish.b",
"fish.b","fish.b"),
Capture = c("","","handling", "", "", "handling") ,
Dive_id =c("dive.1", "dive.1","dive.1", "dive.1","dive.1", "dive.1"))
temp<- tapply(events$Capture, events$Dive_id, function(x) rle(x ==
"handling"))
ncaptures<- data.frame(id = names(temp),
tally = unlist(lapply(temp, function(x) sum(x$values))))
final<-ncaptures[order(ncaptures$id),]
我的最终输出(我将绑定到更大的 data.frame)应该是这样的:
final <- data.frame(fish.a =c(1),
fish.b = c(1),
Dive_id =c("dive.1"))
【问题讨论】:
-
您可以使用聚合函数找出单次潜水捕获的猎物总数
-
@Hunaidkhan 是的,我尝试通过潜水进行汇总,但它不可靠,因为我从 Prey_present 列中获得的数字不能反映被捕获的实际数量。
-
你能做一件事,只提供预期输出的截图或 dput(),我会帮你写代码。
-
table(events1$Dive_id,events1$Prey_present) 这会起作用
-
@Hunaidkhan 您的建议给出了“Prey_present”列的计数。我要解决的是在单个 id/dive 中处理 Prey_present 中每个因素的计数。
标签: r function lapply tapply tally