r - 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"))
解决方案
去掉 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
。我可能又误会了你,所以我向你道歉。
推荐阅读
- webpack - 编写库时的模块名称 Webpack 和 vue-cli
- python - ValueError: no enough values to unpack (expected 2, got 1), Splitting string into two parts with split() didn't work
- php - 我需要使用另一个页面上的数据
- angular - 使用量角器在 Firefox 上下载 PDF 文件不起作用
- java-8 - 如何阅读 Jave 8 元空间转储
- ef-code-first - 需要一种在 Entity Framework Core 中使用 C# Linq 从第二个表中检索数据的方法
- android - 一个屏幕上有两个片段(活动),一个片段如何使用 EventBus 更新另一个片段
- mysql - 如何设计多个值相互遵循的mysql表
- model - 如何将第二个表格模型添加到同一个 SSAS 数据库
- ms-access - 返回用户点击的href内容