【问题标题】:R - Tally for multiple factors in a columnR - 列中多个因素的计数
【发布时间】: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


【解决方案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 的实例。我可能又误会了你,所以我向你道歉。

【讨论】:

  • 您能否将您的输出作为 dput 包含在内?当我运行您建议的代码时,我仍然得到相同的结果(即 prey present 列的总和)
  • 这仍然没有回答我的问题。 preycapture 列表示捕获了某些东西,而不是 prey present 列。因此,捕获了 2 件事。 Fisha 一次和 Fishb 一次。在我的问题中查看我正在寻找的输出。感谢您试一试!
【解决方案2】:
library(dplyr)               
new1<- events %>% group_by(Dive_id,Prey_present) %>% summarise(Capture = NROW(Capture))

这将为您提供所需的输出

【讨论】:

  • 仍然没有给出正确的东西。该代码仍会产生 prey_present 列的计数。 dput(new1) 的输出: structure(list(Dive_id = structure(c(1L, 1L, 1L), .Label = "dive.1", class= "factor"), Prey_present = structure(1:3, .标签 = c("", "fish.a", "fish.b"), class= "factor"), Capture = 1:3), row.names = c(NA, -3L), class= c( “grouped_df”、“tbl_df”、“tbl”、“data.frame”)、vars = list(Dive_id)、drop = TRUE、.Names = c(“Dive_id”、“Prey_present”、“Capture”))跨度>
猜你喜欢
  • 1970-01-01
  • 2014-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-17
  • 1970-01-01
  • 2016-05-07
  • 1970-01-01
相关资源
最近更新 更多