user13608970
user13608970

Reputation: 167

How to calculate the mean given one condition and multiple values in R

I want to calculate the mean given a certain condition is met. And have the code below. How do you rewrite this to get R to do the mean for df$sta== B, C, etc. in one go and provide printed output in the Rstudio console.

 id<-c(1,2,3)
 val<-c(10,15,20)
 sta<-c("A","B","A")

 df<-data.frame(id,val,sta)

 mean(df$val[df$sta=="A"])

Upvotes: 0

Views: 55

Answers (3)

akrun
akrun

Reputation: 886938

We can use aggregate in base R

aggregate(val ~ sta, df, mean)
#  sta val
#1   A  15
#2   B  15

Upvotes: 1

Matt
Matt

Reputation: 2987

Another option:

tapply(df$val, df$sta, mean)


 A  B 
15 15 

Upvotes: 1

Martin Gal
Martin Gal

Reputation: 16978

You could use dplyr:

df %>%
  group_by(sta) %>%
  summarise(mean=mean(val))

gives

# A tibble: 2 x 2
  sta    mean
  <fct> <dbl>
1 A        15
2 B        15

Upvotes: 1

Related Questions