Search code examples
rrowmultiple-columnsmeangroup

Mean by groups by multiple columns in r


I have the next dataframe

obs1   obs2   obs3   zone
1       0      1     Rural
1       1      1     Rural
0       1      1     Urban
1       0      0     Urban
0       1      0     Rural

I am trying to get something like this

Mean Rural    0.6666
Mean Urban    0.5

Is that possible?


Solution

  • To add an {dplyr} approach:

    library(dplyr)
    
    dat %>% 
      group_by(zone) %>% 
      summarise(values = mean(c_across(obs1:obs3)))
    
    #> # A tibble: 2 x 2
    #>   zone  values
    #>   <chr>  <dbl>
    #> 1 Rural  0.667
    #> 2 Urban  0.5
    
    
    # data
    dat <- tibble(obs1 = c(1,1,0,1,0),
           obs2 = c(0,1,1,0,1),
           obs3 = c(1,1,1,0,0),
           zone = c("Rural", "Rural", "Urban", "Urban", "Rural"))
    

    Created on 2022-05-24 by the reprex package (v2.0.1)