问题描述
我想获得移动平均值(例如使用 movavg()
)并从另一列中获得分类变量的相对比例。例如,采用以下数据框:
data.frame('employee'=1:8,'pastjob'=c('sales','sales admin','sales','ops','R&D','IT'),'results'=c(150,200,250,300,125,150,175,150))
我想为“结果”列中的每四个值获得一个简单的移动平均值,并获得其他列中“过去作业”的相对比例。所以,输出将是:
225 - 销售 (50%)、销售管理 (50%)、运营 (0%)、研发 (0%)、IT(0%)
150 - 销售 (0%)、销售管理 (0%)、运营 (50%)、研发 (25%)、IT(25%)
解决方法
您好,只需将索引大小的数字替换为 4
library(tidyverse)
df_example <- data.frame('employee'=1:8,'pastjob'=c('sales','sales admin','sales','ops','R&D','IT'),'results'=c(150,200,250,300,125,150,175,150))
df_example %>%
mutate(index = rep(1:(n()/4),each = 4)) %>%
group_by(index,pastjob) %>%
summarise(total_sales = sum(results),ns = n()) %>%
mutate(prop = total_sales/sum(total_sales),group_mean = sum(total_sales)/sum(ns)) %>%
select(index,pastjob,prop,group_mean) %>%
pivot_wider(values_from = prop,names_from = pastjob,values_fill = 0)
#> `summarise()` has grouped output by 'index'. You can override using the `.groups` argument.
#> # A tibble: 2 x 7
#> # Groups: index [2]
#> index group_mean sales `sales admin` IT ops `R&D`
#> <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 1 225 0.444 0.556 0 0 0
#> 2 2 150 0 0 0.25 0.458 0.292
由 reprex package (v0.3.0) 于 2021 年 1 月 20 日创建