【问题标题】:Windowed (partitioned) % calculation using base R [duplicate]使用基本 R 的窗口化(分区)百分比计算 [重复]
【发布时间】:2019-05-02 17:45:38
【问题描述】:

我有下面的数据框

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

我希望将每个季节的收入计算为总收入的百分比(在每个产品的分区内),以便最终表创建以下列

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 和用户定义函数的组合来实现这一点。

任何帮助将不胜感激。

【问题讨论】:

  • 使用aveave(df$revenue, df$product, FUN = function(x) x/sum(x))
  • @Ronak Shah @akrun 感谢你们两位的及时贡献。两种解决方案都有效。我现在已经通过 with(df, income/ave(revenue, list(season, new_variable), FUN = sum)) 将它应用于多个变量分区我会在 sqldf 中这样做,但你的解决方案更紧凑。谢谢。

标签: r partition


【解决方案1】:

我们可以按部门分组

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

【讨论】:

    猜你喜欢
    • 2016-02-22
    • 1970-01-01
    • 2018-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-20
    • 1970-01-01
    • 2013-05-05
    相关资源
    最近更新 更多