r - 按类别分组并按行 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 XX
a -0.17
b -0.38
每个百分比的公式为:
( counts of c(6,7)
- counts of c(1,2,3,4)
) / counts of c(1,2,3,4,5,6,7)
. 例如,要获取-0.17
for a
:
Where the columns are all (`X1, X2, X3`) and `YY = a`, then:
prom = counts of c(6,7) = 3
detr = counts of c(1,2,3,4) = 5
total = counts of c(1,2,3,4,5,6,7) = 12
The percentage is (prom - detr) / total = (2-3)/ 9 = -0.17
但是,我只能在使用时计算每列summarize_all()
:
df %>%
group_by(YY) %>%
summarize_all(~ (sum(.x %in% 6:7) - sum(.x %in% 1:4)) / sum(.x %in% 1:7))
YY X1 X2 X3
<chr> <dbl> <dbl> <dbl>
1 a -0.333 -1 0.333
2 b 0.167 -0.714 -0.667
当我要计算给定类别的所有列时YY
,而不是每列(如上面所需的输出所示)。
解决方案
可以试试:
library(tidyverse)
df %>%
gather(key, val, -YY) %>%
group_by(YY) %>%
summarise(
XX = ( sum(val %in% 6:7) - sum(val %in% 1:4) ) / sum(val %in% 1:7)
)
输出:
# A tibble: 2 x 2
YY XX
<chr> <dbl>
1 a -0.167
2 b -0.375
推荐阅读
- android - 对将 API 密钥更改为实时项目的影响?
- laravel - 如何在 laravel 中设置 toIso8601String 时区?
- r - R如何为每年分配相同的值范围
- javascript - 如何在 Flutter 中通过 js URL 创建飞镖句柄
- debugging - DDPG 代理具有非减少的批评损失
- django - django API,“类型不正确。预期的 pk 值,已收到 str。”
- python - 更改点数时如何使 pyplot 网格保持对数?
- python - 向稀疏矩阵中的特定元素添加值
- html - CSS:将两个文本在其顶行彼此相邻对齐
- python - 使用 ast 时出现类型错误