使用基本 R 的窗口化(分区)% 计算

Windowed (partitioned) % calculation using base R

我有下面的数据框

df = data.frame(season = rep(seq(1,4),2)
                ,product = c(rep('A', 4), rep('B', 4))
                ,revenue = 1:8
                )

我希望计算每个季节的收入占总收入的百分比(在每个产品的分区内),这样末尾 table 就会创建以下列

df$pc = c(0.1, 0.2, 0.3, 0.4, 0.19, 0.23, 0.27, 0.31)

我知道这可以通过此处讨论的 dplyr 等软件包实现: Summarizing by subgroup percentage in R 但是,挑战在于使用基本 R 函数或基本 R 和用户定义函数的组合来实现这一点。

如有任何帮助,我们将不胜感激。

我们可以做一个分组

library(dplyr)
df %>%
  group_by(product) %>% 
  mutate(pc = round(revenue/sum(revenue), 2))

如果我们需要base R,使用ave

df$pc <- with(df, revenue/ave(revenue, product, FUN = sum))