Equivalent of by in tidyverse ecosystem

Viewed 38

I was wondering how to match the output of my group_by %>% ... command so it become similar to my by(...) command?

library(MASS)
library(tidyverse)
set.seed(0)

dd <- data.frame(mvrnorm(40, 0:2, matrix(c(3,1,1,1,3,1,1,1,3),3,3)), k=rep(1:2, each=20))
by(dd[-4], dd$k, function(i) det(cov(i)))

#dd$k: 1
#[1] 16.62934
#--------------------------------------------------------------- 
#dd$k: 2
#[1] 3.849242

# Equivalent of above in tidyverse:
group_by(dd, k) %>% cov() %>% det()  # doesn't match above
#[1] 2.43671
2 Answers

We can use group_by + summarise combination. Use cur_data() to pass data to cov function.

library(dplyr)  
library(MASS)

dd %>%
  group_by(k) %>%
  summarise(res = det(cov(cur_data())))

#      k   res
#* <int> <dbl>
#1     1 16.6 
#2     2  3.85

We can use group_split

library(dplyr)
library(MASS)
library(purrr)
dd %>%
    group_split(k) %>%
    map(~ det(cov(.x)))
                
Related