Search code examples
rconditional-statementslapplymeansapply

Conditional Mean Statement Across Dataframe


The following code will return the average conditioned that the months are greater than 6.

mean(df[df$delta1>6, "delta1"], na.rm=T)

Now, how do I do apply this for every column in the dataframe?

df:

delta1      delta2      delta3
NA          2           3
4           NA          6
7           8           NA
10          NA          12
NA          14          15
16          NA          18
19          20          NA

Solution

  • The apply-family of functions is useful here:

    sapply(df, function(x) mean(x[x>6], na.rm=T))