首页 > 解决方案 > 考虑另一列中变量的相对比例,获取移动平均值

问题描述

我想获得移动平均值(例如使用movavg())并从另一列获得分类变量的相对比例。例如,采用以下数据框:

data.frame('employee'=1:8, 'pastjob'=c('sales','sales admin','sales','sales admin','ops','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%)

标签: rmoving-average

解决方案


嗨,只需将 4 替换为索引大小的数字

library(tidyverse)

df_example <- data.frame('employee'=1:8, 'pastjob'=c('sales','sales admin','sales','sales admin','ops','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 包(v0.3.0)于 2021 年 1 月 20 日创建


推荐阅读