Apply dplyr function to all but one column

Given a data frame with numeric values โ€‹โ€‹in all columns except the last one, how can I calculate the average over the row?

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

I would like to omit.

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

      

Required dataframe 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

      

+3


source to share


2 answers


In the settings you can use



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

      

+1


source


You may try:



df %>% 
  mutate(mean = select(., -matches("name")) %>% rowMeans(.))

      

+11


source







All Articles