Search code examples
rdata-analysis

Mean and standart deviation by groups where a condition is satisfied


I have such a data frame(df) which is just a sapmle:

group  condition values
1      0         12    
1      1         15 
1      1         23 
1      1         14
2      1         34          
2      1         37
2      0         31
2      0         36
2      1         35

Namely;

df<-data.frame(group=c(1, 1, 1, 1, 2, 2, 2, 2, 2 ),
           condition=c(0,1,1,1,1,1,0,0,1), 
           values=c(12,15,23,14,34,37,31,36,35)) 

I want to find

  • standart deviation and mean of "values"

  • for each "group"

  • where "condition=1".

How can I do that? Is there any way doing that wihout subsetting? Thanks a lot. I will be very greatful for any help.


Solution

  • You could use a data.table like this:

    library(data.table)
    ##
    dt <- data.table(df)
    ##
    R>  dt[condition==1,
         .(Mean=mean(value),Sd=sd(value)),
         by=group]
       group     Mean       Sd
    1:     1 17.33333 4.932883
    2:     2 35.33333 1.527525