JiaxiangBU / tutoring2

The collection of Python and R code scripts to tutor others.
https://jiaxiangbu.github.io/tutoring2/
Other
8 stars 7 forks source link

R实现python的分组+统计+unstack #18

Closed slsongge closed 4 years ago

slsongge commented 4 years ago

简述问题

如何用R实现python的如下功能:

df.groupby(['fct_1', 'fct_2'])['num_1'].agg(['count','mean']).unstack()

数据代码

library(plyr)
library(tidyverse)

df <- data.frame(fct_1 = letters[1:4], fct_2 = LETTERS[1:4], num_1 = c(0,0,1,0)); df

df %>%
  group_by(fct_1, fct_2) %>%
  summarise(
    cnt  = n(),
    rate = mean(num_1)
  )
JiaxiangBU commented 4 years ago

根据讨论,加上

gather(key, value, -fct_1, -fct_2)

即可。