Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply dplyr function to all but one column

Tags:

r

dplyr

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
like image 400
Megatron Avatar asked Dec 05 '22 20:12

Megatron


1 Answers

You could try:

df %>% 
  mutate(mean = select(., -matches("name")) %>% rowMeans(.))
like image 175
Steven Beaupré Avatar answered Jan 26 '23 01:01

Steven Beaupré