[R] apply function across dataframe columns for non-exclusive groups

Alexander Shenkin ashenkin at ufl.edu
Wed Oct 21 13:30:46 CEST 2015


Hello all,

I've been banging my head over what must be a simple solution.  I would 
like to apply a function across columns of a dataframe for rows grouped 
across different columns.  These groups are not exclusive.  See below 
for an example.  Happy to use dplyr, data.table, or whatever.  Any 
guidance appreciated!

Thanks,
Allie


desired algorithm: calculate a/(a+b) for each TRUE and FALSE grouping of 
columns grp1 and grp2.

this_df = data.frame(a = c(1,2,3,4,5), b = c(7,8,9,10,11), grp1 = 
c(T,T,F,F,F), grp2 = c(F,T,F,T,F))

desired output (doesn't have to be exactly this format, but something 
along these lines):

grp1 T 0.166
grp1 F 0.286
grp2 T 0.25
grp2 F 0.25



More information about the R-help mailing list