Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calculate a mean by criteria in R

Tags:

r

mean

I would like to calculate a sample mean in R by introducing a specific criteria. For example I have this table and I want the means of only those for whom stage = 1 or 2:

treatment session period stage wage_accepted type 
1            1      1     1            25  low 
1            1      1     3            19  low 
1            1      1     3            15  low 
1            1      1     2            32 high 
1            1      1     2            13  low 
1            1      1     2            14  low 
1            1      2     1            17  low 
1            1      2     4            16  low
1            1      2     5            21  low

The desired out in this case should be:

   stage  mean
      1  21.0 
      2  19.6667

Thanks in advance.

like image 873
rado Avatar asked Jan 09 '23 13:01

rado


1 Answers

With the dplyr library

library(dplyr)

df %>% filter(stage==1 | stage ==2) %>% group_by(stage) %>%
  summarise(mean=mean(wage_accepted))

If you are new to dplyr a bit of explanation:

Take the data frame df then filter where stage is equal to 1 or 2. Then for each group in stage calculate the mean of the wage_accepted

like image 72
dimitris_ps Avatar answered Jan 18 '23 11:01

dimitris_ps