gpt4 book ai didi

r - 计算每年销售额的 Top N 产品

转载 作者:行者123 更新时间:2023-12-05 09:27:56 25 4
gpt4 key购买 nike

我有关于年销售额和副产品的数据,我们可以这样说:

Year <- c(2010,2010,2010,2010,2010,2011,2011,2011,2011,2011,2012,2012,2012,2012,2012)
Model <- c("a","b","c","d","e","a","b","c","d","e","a","b","c","d","e")
Sale <- c("30","45","23","33","24","11","56","19","45","56","33","32","89","33","12")
df <- data.frame(Year, Model, Sale)

我想要按年份标识前 2 名产品并将所有其余产品汇总为类别“其他”的代码。

最佳答案

我们可以按desc结束顺序按'Year'和'Sale'排列,然后在按'Year'分组后根据row_number更改'Model'的值'

library(dplyr)
df %>%
arrange(Year, desc(Sale)) %>%
group_by(Year) %>%
mutate(Model = case_when(row_number() > 2~ 'other', TRUE ~ Model)) %>%
ungroup

或者另一种选择是使用slice_max(默认情况下with_ties = TRUE)

df %>%
group_by(Year) %>%
mutate(Model =case_when(Model %in% {cur_data() %>%
slice_max(n = 2, order_by = Sale) %>%
pull(Model)} ~ Model, TRUE ~ "other" )
)

关于r - 计算每年销售额的 Top N 产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71927757/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com