Search code examples
rdplyrtidyverseacross

I R ,how to summarise numeric columns automaticaly. Thanks


I R ,how to summarise numeric columns automaticaly. Thanks

library(tidyverse)
df <- tibble(label=LETTERS[1:8],
             x = rep(2:5, each = 2) / 2, 
             y = rep(2:3, each = 4) / 2)


df %>% sum(across(where(is.numeric))) #can't work
df %>% sum(where(is.numeric)) #can't work

Solution

  • You need to use across inside a dplyr verb, such as mutate or summarize, then you need to define the function you want to apply in .fns, I used mean as an example in your data.

    df %>% summarize(across(.cols = where(is.numeric),.fns = mean))
    
    # A tibble: 1 x 2
          x     y
      <dbl> <dbl>
    1  1.75  1.25