Megatron Megatron - 2 months ago 5
R Question

Apply dplyr function to all but one column

Given a data frame with numeric values in all columns except for the last one, how can I compute the mean across the row?

In this example, I am using all columns, including the

name
column which I would like to omit.

df <- as.data.frame(matrix(1:40, ncol=10)) %>%
mutate(name=LETTERS[1:4]) %>%
mutate(mean=rowMeans(.))


Desired data frame output:

V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 mean name
1 1 5 9 13 17 21 25 29 33 37 19 A
2 2 6 10 14 18 22 26 30 34 38 20 B
3 3 7 11 15 19 23 27 31 35 39 21 C
4 4 8 12 16 20 24 28 32 36 40 22 D

Answer

In your setting, you could use

df <- as.data.frame(matrix(1:40, ncol=10)) %>%
  mutate(name=LETTERS[1:4]) %>%
  mutate(mean=rowMeans(.[,1:10]))
Comments