Apply several summary functions on several variables by group in one call

前端 未结 7 1476
一个人的身影
一个人的身影 2020-11-22 00:03

I have the following data frame

x <- read.table(text = \"  id1 id2 val1 val2
1   a   x    1    9
2   a   x    2    4
3   a   y    3    5
4   a   y    4            


        
7条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 00:06

    Another dplyr option is across which is part of current dev version

    #devtools::install_github("tidyverse/dplyr")
    library(dplyr)
    
    x %>% 
      group_by(id1, id2) %>% 
      summarise(across(starts_with("val"), list(mean = mean, n = length)))
    

    Result

    # A tibble: 4 x 4
    # Groups:   id1 [2]
      id1   id2   mean$val1 $val2 n$val1 $val2
                
    1 a     x           1.5   6.5      2     2
    2 a     y           3.5   7        2     2
    3 b     x           2     8        2     2
    4 b     y           3     6        2     2
    

    packageVersion("dplyr")
    [1] ‘0.8.99.9000’
    

提交回复
热议问题