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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With