How to Find Conditional Mean from one coloum

Can somebody please help me in finding the mean from the following data set of the age of people who are more than 30 years old using r

Name. Age
A 34
B. 22
C. 67
D. 43
E. 10

I'm kind of a newbie. I used the code mean(df$age) but cant set the condition to less than 30.

Using base R you can do the following.

DF <- data.frame(Name = LETTERS[1:5], Age = c(34, 22, 67,43, 10))
mean(DF[DF$Age < 30, "Age"])
#> [1] 16

#Why does that work?
DF$Age < 30  #This returns TRUE and FALSE values
#> [1] FALSE  TRUE FALSE FALSE  TRUE

DF[DF$Age < 30, ] #This returns all rows where the comparison is TRUE
#>   Name Age
#> 2    B  22
#> 5    E  10

DF[DF$Age < 30, "Age"] #Tis returns just the Age column of selected rows
#> [1] 22 10

Created on 2021-07-08 by the reprex package (v0.3.0)

This can be done more elegantly with the dplyr package

library(dplyr)
DF %>% filter(Age < 30) %>% summarize(AvgAge = mean(Age))

Thank you so much for your help!

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.