0

I try to write a simple function to obtain the rate between columns in a dataframe on a aggregated level. I would like to obtain the same output as the output obtained by:

library(dplyr)
set.seed(1)
dat <- data.frame(x = rep(1:3, each = 5), a = runif(15, 0, 1), b = runif(15, 0, 2))

oper_fn <- function(df, oper){
  oper <- enquo(oper)
  df %>%
     group_by(x) %>%
     summarize(output = !! oper) %>%
     ungroup()
}

oper_fn(dat, sum(a) / sum(b))

The following should also work:

oper_fn(dat, sum(a))

What is the way to do this in base R?

mharinga
  • 1,708
  • 10
  • 23

2 Answers2

2

You can just split on x and use sapply to loop over the groups and apply your function, i.e.

sapply(split(dat, dat$x), function(i) sum(i$a) / sum(i$b))
#        1         2         3 
#0.3448112 0.7289661 0.5581262
Sotos
  • 51,121
  • 6
  • 32
  • 66
1

Another option using aggregate

tmp <- aggregate(.~x, dat, sum)
cbind(tmp[1], tmp['a']/tmp['b'])

#  x         a
#1 1 0.3448112
#2 2 0.7289661
#3 3 0.5581262

Or a one liner using transform with aggregate

transform(aggregate(.~x, dat, sum), output = a/b)

#  x        a        b    output
#1 1 2.320376 6.729408 0.3448112
#2 2 3.194763 4.382595 0.7289661
#3 3 2.223499 3.983864 0.5581262
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213