Search code examples
rmeanlevelsfactors

Mean by factor by level


Maybe this is simple but I can't find answer on web. I have problem with mean calculation by factors by level. My data looks typicaly:

factor, value
a,1
a,2
b,1
b,1
b,1
c,1

I want to get vector A contains mean only for level "a" If I type A on consol I want to get 1.5 And this method for calculating mean, must use factors.

Thank you in advance for help.


Solution

  • Just for fun posting the data.table solution although you probably should do what @lukeA suggested

    library(data.table) 
    A <- setDT(df)[factor == "a", mean(value)]
    ## [1] 1.5