How to calculate average value with conditions?

The following is a script to generate a reproducible data frame:

id <- c(1:20)
a <- as.numeric(round(runif(20,-40,40),2))
b <- as.numeric(round(a*1.4+60,2))
df <- as.data.frame(cbind(id, a, b))

I would like to calculate the average value of "b" under another condition of "a". for example, what is the average value of "b" when -40 = <a <0; and what is the average value of "b" when 0 = <<= 40.

Many thanks!

+4
source share
2 answers

Here's a quick fix data.table(if coefequal a)

library(data.table)
setDT(df)[, .(MeanASmall = mean(b[-40 <= a & a < 0]),
              MeanABig = mean(b[0 <= a & a <= 40]))]
#    MeanASmall MeanABig
# 1:   33.96727    89.46

If the range is alimited, you can do it fast with R base too

sapply(split(df, df$a >= 0), function(x) mean(x$b))
#     FALSE     TRUE 
#  33.96727 89.46000 
+2
source

The following solutions will do this:

Subset

ndf1<-subset(df, a>=-40 & a<=0)
ndf2<-subset(df, a>=0 & a<=40)

mean(ndf1[,3])
mean(ndf2[,3])

Or easier

mean(df[a>=-40 & a<=0, 3]) 
mean(df[a>=0 & a<=40, 3]) 

Using ddply

library(plyr)
ddply(df, .(a>=-40 & a<=0), summarize, mean=mean(b))
ddply(df, .(a>=0 & a<=40), summarize, mean=mean(b))
+4

All Articles