如何在保留原始数据帧的同时获取组级统计信息?
问题描述:
我有以下数据框
one <- c('one',NA,NA,NA,NA,'two',NA,NA)
group1 <- c('A','A','A','A','B','B','B','B')
group2 <- c('C','C','C','D','E','E','F','F')
df = data.frame(one, group1,group2)
> df
one group1 group2
1 one A C
2 <NA> A C
3 <NA> A C
4 <NA> A D
5 <NA> B E
6 two B E
7 <NA> B F
8 <NA> B F
我想获得个
,分别用于 group1
和 group2
的每个组合。
I want to get the count of non-missing observations of one
for each combination of group1
and group2
.
在熊猫中,我会使用 groupby(['group1','group2'])。transform
,但是如何在R中做到这一点?原始数据帧为大数据。
In Pandas, I would use groupby(['group1','group2']).transform
, but how can I do that in R? The original dataframe is LARGE.
预期输出为:
> df
one group1 group2 count
1 one A C 1
2 <NA> A C 1
3 <NA> A C 1
4 <NA> A D 0
5 <NA> B E 1
6 two B E 1
7 <NA> B F 0
8 <NA> B F 0
非常感谢!
答
:
setDT(df)
df[,count_B:=sum(!is.na(one)),by=c("group1","group2")]
给予:
one group1 group2 count_B
1: one A C 1
2: NA A C 1
3: NA A C 1
4: NA A D 0
5: NA B E 1
6: two B E 1
7: NA B F 0
8: NA B F 0
想法是对真实值求和(将1转换为整数),其中B不是 NA
,而按 group1
分组,然后 group2
。
The idea is to sum the true values (1 once converted to integer) where B is not NA
while grouping by group1
and group2
.