I have seen several posts on getting rowMeans type of result in mutate. For example and dplyr - using mutate() like rowmeans() -- But I want to have another variable act as a filter.
I understand that this data is not tidy, and the "f#" and "d#" variables could be reshaped long, and then cast to "f" and "d", then filter on "f" and summarize "d". But is there a way to do this without reshape? I devised the code below
library(tidyverse)
x<-data.frame(f1=c(1,1), f2=c(1,0), f3=c(1,1),
d1=c(3,2), d2=c(4,8), d3=c(8,16))
x
x %>%
rowwise() %>%
mutate(agg=sum(f1*d1, f2*d2, f3*d3) / sum(f1, f2, f3) )
#Source: local data frame [2 x 7]
#Groups: <by row>
# A tibble: 2 x 7
# f1 f2 f3 d1 d2 d3 agg
# <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1 1.00 1.00 1.00 3.00 4.00 8.00 5.00
#2 1.00 0 1.00 2.00 8.00 16.0 9.00
But, I lose the ability to use ranges when there are many variables, so I cannot say "f1*d1":"f2*d2" - is there some more general way?