本文介绍了按组对行进行计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码:

Group <- rep(c("A", "B", "C"), each = 3)
Days <- c(21,21,19,18,21,21,11,21,19)
State <- c("OK", "NOK", "OK", "OK", "NOK", "OK", "OK", "OK", "NOK")

data <- data.frame(Group = Group, Days = Days, State = State)

创建此数据框:

> data
  Group Days State
1     A   21    OK
2     A   21   NOK
3     A   19    OK
4     B   18    OK
5     B   21    OK
6     B   21    OK
7     C   11   NOK
8     C   21    OK
9     C   19   NOK

我经常使用 group_by 并总结 dplyr 确实获取组的参数(例如A,B,C)。但是我想不出一种简单的方法来获得每个组的OK和NOK(例如,NOK百分比)的困扰。我期望的结果是:

I often use group_by and summarizes of dplyr do get parameters of groups (eg. A, B, C). But I couldn't figure ou a simple way to get the amnount of OKs and NOKs per Group (eg. percentage NOK). The result I expect would by:

  > result
      Group   %NOK
    1     A   33.3
    2     B      0
    3     C   66.6

我想进一步计算带有其他条件的比例。例如:计算NOK的数量,其中每个组的天数> 20。我真正直接的解决方案是:

In a further step I wish to count proportions with additional conitions. For example: Count the amount of NOKs, where days > 20 for every group. My really straightforward solution would be:

data %>% group_by(Group) %>% nrow(filter(Days < 20, State == "NOK")) / n() * 100

很好,如果您能给我一个解决方案,那实际上是有效的;)

but it would be nice, if you could give my a solution, that is actually working ;)

推荐答案

我们可以使用总结

data %>%
   group_by(Group) %>%
   summarise(NOKPer = round(100*sum(State=="NOK")/n(),2))
#     Group NOKPer
#    (chr)  (dbl)
# 1     A  33.33
# 2     B   0.00
# 3     C  66.67

第二种情况

data %>%
    group_by(Group) %>%
    summarise(NOKPer = round(100*sum(State=="NOK" & Days >20)/n(), 2))






使用 base R

prop.table(table(data[-2]),1)

并具有第二个条件

prop.table(table(subset(data, Days>20, select=c("Group", "State"))),1)

这篇关于按组对行进行计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 20:37