总结基数R中的数据

问题描述 投票:0回答:2

我尝试编写一个简单的函数来获取聚合级别的数据框中列之间的比率。我想获得与通过以下方式获得的输出相同的输出:

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))

以下也应该有效:

oper_fn(dat, sum(a))

在基地R中这样做的方法是什么?

r dplyr nse
2个回答
2
投票

您可以拆分x并使用sapply循环组并应用您的功能,即

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

1
投票

使用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

或使用transformaggregate的一个班轮

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
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.