Home > Back-end >  Grouping with TRUE/FALSE in Tidyverse
Grouping with TRUE/FALSE in Tidyverse

Time:11-13

I have a dataset with the following layout (random example):

set.seed(1)

data <- tibble(A = sample(c(TRUE, FALSE), 10, replace = T), B = sample(c(TRUE, FALSE), 10, replace = T), C = sample(c(TRUE, FALSE), 10, replace = T), value = sample(1:100, 10))

For each combination of A, B and C I want to calculate the mean(value). Ideally, I want a new tidy tibble with these combinations of A, B and C and the result (including A, AB, ABC, AC, etc - all possible combinations of A/B/C if).

Here, rows 1,3 and 4 are all ABC which would result in

ABC - mean(89, 79, 33)

For row 2,5 B,C - mean(44,84)

How would I go about this?

CodePudding user response:

A simple solution is to use dplyr: group_by the variables A, B, C, then summarise the mean of the values:

library(dplyr)
dat2<-dat%>%
  group_by(A,B,C)%>%
  summarise(Mean = mean(value))
  • Related