Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Conditional mean from different column

I do have an R data frame like this:

city2001 <- c('a', 'b', 'a')
grade2001 <- c(5, 5, 7)
city2002 <- c('b', 'b', 'a')
grade2002 <- c(8, 9, 10)

df <- data.frame(city2001, grade2001, city2002, grade2002)

and would like to return ,

avg_a = 7.333
# from (5 + 7 + 10)/3

How is the logic for that? Thanks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try

mean(df[,grepl("grade",colnames(df))][df[,grepl("city",colnames(df))]=="a"])
[1] 7.333333

your df (columns) better be sorted.

If you want for all the groups and not just "a"

tapply(
  unlist(df[,grepl("grade",colnames(df))]),
  unlist(df[,grepl("city",colnames(df))]),
  mean
)
       a        b 
7.333333 7.333333
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading