Conditional statement and calculating mean

Hello,

How do I calculate mean from a given column using a conditional statement ie if a certain variable has a true value only then it should be considered.
image

For instance= I would only like to calculate the mean age from the above table of all males who have jobs "e"

Let's assume yo data are in a data frame named df. You can get the average Age of Gender == "M" and Job == "E" with

library(dplyr)
df %>% filter(Gender == "M", Job == "E") %>% summarize(Avg = mean(Age))

You can get the average of all combinations of Gender and Job with

library(dplyr)
df %>% group_by(Gender, Job) %>% summarize(Avg = mean(Age))
1 Like

Or if you for some odd reason don't want to use dplyr, you can use vanilla R:

mean(df$Age[df$Gender == "M" & df$Job == "E"])
1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.