I have the following table with sample data:
set.seed(10)
dat <- data.frame(grp1 = sample(c(0, 1), size = 5, replace = TRUE),
grp2 = sample(c(0, 1), size = 5, replace = TRUE),
grp3 = sample(c(0, 1), size = 5, replace = TRUE),
value = round(runif(5, min = 0, max = 10), 0) )
dat
grp1 grp2 grp3 value
1 0 0 0 4
2 0 1 1 1
3 1 1 0 3
4 1 0 0 4
5 1 0 1 8
But in the end, I need a tibble like this:
group mean
-----------------------
grp1 5.0
grp2 2.0
grp3 4.5
Usually, I would do a pivot_longer(cols = starts_with("grp")), so I could easily group_by(name) and calculate the groupwise means using summarise(mean = mean(value, na.rm=TRUE)). But here my problem is, that each of the 5 elements can belong to multiple groups (grp1, grp2, grp3), so there's some overlapping between the groups. My naive attempt would be to calculate the means for each group separately and then rbind() them. But as the number of groups increases this gets annoying, so I am looking for a way to automate this.