为特定条件创建计数表,然后在R中添加按组整体创建计数的列

lh80um4z  于 2023-07-31  发布在  其他
关注(0)|答案(2)|浏览(68)

我有一张这样的table:

data1 <- data.frame("State" = c("NJ", "NJ", "PA", "NJ", "TX"), "Filter" = c("Filter", "Filter", 
"No Filter", "Filter", "Filter"), "Threshold" = c("Exceeds","Exceeds", NA, "NL", "Exceeds"))

字符串
我想创建一个计数表,按状态和过滤器分组,然后计算阈值为“超出”的次数,并将该值放入新列中。然后计算某个State和Filter组合出现的次数,并将其放在另一列中。下面是我正在寻找的一个例子。

final_data <- data.frame("State" = c("NJ", "NJ", "PA", "NJ", "TX"), "Filter" = c("Filter", 
"Filter", "No Filter", "Filter", "Filter"), "Threshold" = c("Exceeds", "Exceeds", NA, "NL", 
"Exceeds"), Count_Exceeds_Threshold = c(2, 2, 0, 0, 1), Count_Total = c(3, 3, 1, 3, 1))


我已经尝试在dplyr中使用group_by和tally()来解决这个问题,但是我不能让它以我想要的方式工作。
谢谢你!

h79rfbju

h79rfbju1#

您可以将add_count()用于以下两种目的:

library(dplyr)

data1 %>%
  group_by(State, Filter) %>%
  add_count(wt = (Threshold == "Exceeds"), name = "Count_Exceeds_Threshold") %>%
  add_count(name = "Count_Total") %>%
  ungroup()

# # A tibble: 5 × 5
#   State Filter    Threshold Count_Exceeds_Threshold Count_Total
#   <chr> <chr>     <chr>                       <int>       <int>
# 1 NJ    Filter    Exceeds                         2           3
# 2 NJ    Filter    Exceeds                         2           3
# 3 PA    No Filter NA                              0           1
# 4 NJ    Filter    NL                              2           3
# 5 TX    Filter    Exceeds                         1           1

字符串

iecba09b

iecba09b2#

您可以使用mutate.by进行内联分组,并计算Threshold == "Exceeds"的次数。n()用于按组获取行数。

library(dplyr)
data1 %>% 
  mutate(Count_Exceeds_Threshold = sum(Threshold == "Exceeds", na.rm = TRUE),
         Count_Total = n(), .by = c(State, Filter))

#   State    Filter Threshold Count_Exceeds_Threshold Count_Total
# 1    NJ    Filter   Exceeds                       2           3
# 2    NJ    Filter   Exceeds                       2           3
# 3    PA No Filter      <NA>                       0           1
# 4    NJ    Filter        NL                       2           3
# 5    TX    Filter   Exceeds                       1           1

字符串

相关问题