Reputation: 167
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
Reputation: 886938
We can use aggregate
in base R
aggregate(val ~ sta, df, mean)
# sta val
#1 A 15
#2 B 15
Upvotes: 1
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