0

I have the following data in a tibble:

df <- tribble(~id, ~x, ~y, ~z,
              1, 4.1, 3.1, 2.4,
              1, 3.2, 2.4, 2.5,
              2, 1.4, 4.0, 7.0,
              2, 5.6, 1.2, 7.1,
              3, 7.8, 1.6, 2.3,
              3, 2.4, 2.5, 1.2
              )

What I want to do is mean over the 3 variables x, y & z to produce a single value for each id value. I can do this using the following code:

f <- df %>% group_by(id) %>% summarize(x=mean(x), y=mean(y), z=mean(z))

The question is how do I generalise this if I had say 100 variables rather than just the 3.

Regards, Alan.

olooney
  • 2,467
  • 1
  • 16
  • 25

1 Answers1

1

Do you mean this?

df %>% group_by(id) %>% summarise_all(mean)
## A tibble: 3 x 4
#     id     x     y     z
#  <dbl> <dbl> <dbl> <dbl>
#1    1.  3.65  2.75  2.45
#2    2.  3.50  2.60  7.05
#3    3.  5.10  2.05  1.75
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68