我有一个数据框,在一年中的每个季节有3个陷阱会话,为期3年(真正的数据库有超过100个季节和800个陷阱季节)。 对于每个诱捕季节,我有3个二项式变量(“Non_Breeder”,“Potential_Breeder”和“Breeding”)。
# example
Year <- c(rep(2000,12), rep(2001,12), rep(2002,12))
Season <- c(rep (seq(1:4), each=3,3))
Trap_Session <- seq(1:36)
Non_Breeder <- (rbinom(36, 1, prob=0.5))
Potential_Breeder <- (rbinom(36, 1, prob=0.8))
Breeding <- (rbinom(36, 1, prob=0.4))
Month <- sample(12, 36, replace = TRUE)
db <- cbind (Year, Season, Trap_Session, Non_Breeder, Potential_Breeder, Breeding)
db <- as.data.frame (db)
我想为每个季节计算“(Potential_Breeder + Breeding)/(Non_Breeder + Potential_Breeder + Breeding)”,保持变量“Year”,“Season”和“Ratio”。
我尝试使用函数table
,但我不知道如何自动为每个季节制作一个循环并保持变量“Year”,“Season”和“Ratio”。
例如: 如果我有以下数据:
Year Season Trap_Session Non_Breeder Potential_Breeder Breeding
1 2000 1 1 1 1 0
2 2000 1 2 1 1 0
3 2000 1 3 0 1 0
4 2000 2 4 0 1 1
5 2000 2 5 1 1 1
6 2000 2 6 1 1 1
我想得到:
Year Season Ratio
2000 1 0.6 # (3/5)
2000 2 0.75 # (6/8)
#Explanation of the calculation
# 2000 Season 1
(3 Potential_Breeder / 5 (3Potential_Breeder+2 Non_Breeder)
# 2000 Season 2
(3Potential_Breeder + 2Breeding / 2Non_Breeder + 3Potential_Breeder +2Breeding)
有谁知道怎么做?
答案 0 :(得分:2)
试试这个:
library(data.table)
setDT(db)[ , .("Ratio" = sum(Potential_Breeder, Breeding) /
sum(Non_Breeder, Potential_Breeder, Breeding)), by = .(Year, Season)]
这会添加一个名为&#34; Ratio&#34;的变量。 (按照您的意愿命名)按年份和季节对现有数据进行分组,
与dplyr相同:
library(dplyr)
group_by(db, Year, Season) %>% summarise("Ratio" = sum(Potential_Breeder, Breeding) /
sum(Non_Breeder, Potential_Breeder, Breeding))
两者都给出了以下输出,给出了OP中的db:
Year Season Ratio
1: 2000 1 0.8000000
2: 2000 2 0.5000000
3: 2000 3 0.6000000
4: 2000 4 0.8000000
5: 2001 1 0.6666667
6: 2001 2 0.8000000
7: 2001 3 0.8000000
8: 2001 4 0.6000000
9: 2002 1 1.0000000
10: 2002 2 0.5000000
11: 2002 3 0.8571429
12: 2002 4 0.6666667
答案 1 :(得分:1)
数据结构中缺少月份!然而,一个解决方案:
# Columns you want to group by
grp_cols <- names(db)[-c(3,4,5,6)]
# Convert character vector to list of symbols
dots <- lapply(grp_cols, as.symbol)
db %>%
group_by_(.dots = dots) %>%
summarise(SumNB = sum(Non_Breeder), SumB = sum(Breeding), SumPB = sum(Potential_Breeder)) %>%
mutate(Ratio = (SumPB + SumB) / (SumNB + SumPB + SumB))
应该这样做。
编辑:对应于您对grrgrrblas答案的第3条评论,此脚本汇总了B,NB和PB的所有计数,然后计算比率。