首页 > 解决方案 > R - 列中多个因素的计数

问题描述

我有一个示例 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"))                    

标签: rfunctionlapplytapplytally

解决方案


去掉 Capture 列,使用dplyr库进行聚合

library(dplyr)

capture_tally <- events %>% group_by(Dive_id, Prey_present) %>% 
    summarise(Count_of_Captures = n())

它将按 Dive_id 和 Prey_Present 分组。然后使用该summarise函数对捕获的每个特定潜水和猎物类型进行计数。

您可以随意命名该Count_of_Captures列。

编辑:这是上面代码的输出。

 Dive_id        Prey_present         Count_of_Captures
  <fctr>       <fctr>               <int>
1  dive.1                              1
2  dive.1       fish.a                 2
3  dive.1       fish.b                 3

编辑:好的,试试这个。

library(tidyr); 

events %>% group_by(Dive_id, Prey_present) %>% 
   filter(Capture != "") %>%  # filter out captured ones (handling)
   summarise(Count = n()) %>%  #get the count for each fish type (long format)
   spread(Prey_present, Count) # Use the spread() function from tidyr package to convert the data from long to wide format

我猜你在任何时候捕获栏都是空白的,没有捕获任何鱼。并且您只计算它所说的实例handling。我可能又误会了你,所以我向你道歉。


推荐阅读