Search code examples
rsummarizeacross

Summarise(across(where)) in R


I have the following data file called "data_2":

Person Weight Height
A      55     155
B      65     165
C      75     175

I wanna use the Summarise(across(where))-command in order to generate the total weight and the weight for each person. This is what I have tried until now.

data_2 <- read_excel("data_2.xlsx", sheet = 2)


data_2 %>%
summarise(across(where(is.numeric), sum))

Unfortunately, this don't work correctly. Does anyone have an idea on how to solve this?

Expected output:

Person Weight 
A      55     
B      65     
C      75
Total  195   

Solution

  • Try this:

    library(dplyr)
    #Code
    newdf <- data_2 %>%
      bind_rows(data_2 %>% select(-1) %>%
                  summarise_all(sum) %>% mutate(Person='Total'))
    

    Output:

      Person Weight Height
    1      A     55    155
    2      B     65    165
    3      C     75    175
    4  Total    195    495
    

    Or using your code:

    #Code 2
    newdf <- data_2 %>% 
      bind_rows(data_2 %>% summarise(across(where(is.numeric),sum)) %>%
                  mutate(Person='Total')) %>% select(-Height)
    

    Output:

      Person Weight
    1      A     55
    2      B     65
    3      C     75
    4  Total    195