简体   繁体   中英

Summarize data in base R

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?

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

sapply(split(dat, dat$x), function(i) sum(i$a) / sum(i$b))
#        1         2         3 
#0.3448112 0.7289661 0.5581262

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM