首页 > 解决方案 > 按类别分组,同时计数、求和和除法 - R

问题描述

我有这个数据框:

> set.seed(100)
> df <- data.frame(X1 = sample(c(1:7, NA), 10, replace=TRUE),
                 X2 = sample(c(1:7, NA), 10, replace=TRUE),
                 X3 = sample(c(1:7, NA), 10, replace=TRUE),
                 YY = sample(c("a","b"), 10, replace=TRUE),
                 stringsAsFactors = FALSE)

> df
   X1 X2 X3 YY
1   3  5  5  a
2   3 NA  6  b
3   5  3  5  a
4   1  4  6  b
5   4  7  4  b
6   4  6  2  b
7   7  2  7  a
8   3  3 NA  b
9   5  3  5  b
10  2  6  3  a

最终输出是这样的:

YY   X1     X2    X3
 a  -0.25  -0.25  0
 b  -0.83  -0.2   0

每个百分比的公式为:

( counts of c(6,7)- counts of c(1,2,3,4)) / counts of c(1,2,3,4,5,6,7). 例如,要获取-0.5forX1a

Where the columns is `X1` and `YY = a`, then:
prom = counts of c(6,7) = 1 
detr = counts of c(1,2,3,4) = 4 
total = counts of c(1,2,3,4,5,6,7) = 6 
The percentage is (prom - detr) / total = (1-4)/ 6 = -0.5

我正在尝试通过每列 ( X1,X2, and X3) 上的循环来实现该输出,其中,对于每一列:

 > table(df[,X1], df$YY)
    a b
  1 0 1
  2 1 0
  3 1 2
  4 0 2
  5 1 1
  7 1 0

a并将和的相应计数相加b。但是我正在努力访问它table(),并且对于每个YY,将各自的计数相加,休息它们,然后将它们除以计数总数。我正在考虑使用 访问表格并按标准求和expss::sum_if(),但我仍然想不出办法。

有更简单的方法吗?任何的想法?。我也尝试使用 dplyr,但是当我必须按类别分组并按列计数、求和和除以并以那个小输出结束时,它似乎更复杂。

标签: rgroup-bydplyr

解决方案


get_ratio我们可以根据我们的公式创建一个函数

get_ratio <- function(x) {
  (sum(x %in% 6:7) - sum(x %in% 1:4))/sum(x %in% 1:7)
}

现在将它应用于每个组 ( YY)

library(dplyr)

df %>%
  group_by(YY) %>%
  summarise_at(vars(X1:X3), get_ratio)

#    YY       X1     X2    X3
#   <fct>    <dbl>  <dbl> <dbl>
#1    a     -0.5     -1     0
#2    b      0.25    -1    -1

推荐阅读