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 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.5
forX1
和a
:
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,但是当我必须按类别分组并按列计数、求和和除以并以那个小输出结束时,它似乎更复杂。
解决方案
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
推荐阅读
- sql - 根据条件将表B中的行添加到表A
- ffmpeg - 如何使用 FFmpeg(或 SoX)自动检测和输出音频静音?
- python - 方法同时返回自身和一个值
- python - 找不到退出循环并保留当前输入的变量的方法
- asp.net-mvc - 在单个根文件夹下组织 WebApi 控制器并路由到它们
- android - Kotlin 协程和 SecurityException
- django - 如何为 django summernote 表单传递不同的 id
- reactjs - React 应用程序视频挂起,浏览器显示许多“待处理”流
- sql - 按日期、名称和值的 PIVOT SQL 表
- c# - 进度条超过最大值