r - 考虑另一列中变量的相对比例,获取移动平均值
问题描述
我想获得移动平均值(例如使用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%)
解决方案
嗨,只需将 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 日创建
推荐阅读
- c# - 我可以将奥尔良用于过程中的演员/谷物吗?
- django-models - 在 Django Filter 和 Wagtail 中使用 ModelChoiceFilter 时如何防止重复
- reactjs - 如何使用 jenkins 的 build_number 变量作为 reactjs docker 映像的标签?
- azure-devops - 需要 CI CD 组件信息
- reactjs - 为什么访问 id 在 if 和 else 上的工作方式不同?
- ios - Flutter [iOS] - 创建使用插件的插件
- angular - 类型具有私有属性模拟服务单元测试Angular 7的单独声明
- python - Python请求从按钮获取href url
- python - Python:Numpy将数组的每一行与另一个数组的每一行相乘
- sapui5 - 如何禁用信箱并为宽屏调整 UI5?