我有一份员工实际能力(每个月都在变化)和他们的计划能力(每个月都是不变的)的列表。我想使用 summarise_at 来告诉他们超过(或低于)分配的百分比。但是,我不知道如何通过汇总调用来管理我的自定义函数。我尝试查看此答案,但我的功能不同,因为它需要来自多个列的输入。
这是一个示例数据集:
library(dplyr)
question <- tibble(name = c("justin", "justin", "corey", "corey"),
allocation_1 = c(1, 2, 4, 8),
allocation_2 = c(2, 4, 11, 9),
scheduled_allocation = c(3, 3, 4, 4))
这就是我想要的:
library(dplyr)
answer <- tibble(name = c("justin", "corey"),
allocation_1 = c(100, 300),
allocation_2 = c(200, 500))
这就是我到目前为止所得到的。我知道自定义函数有效——我只是无法让它通过。X 将对应于它们的总分配(例如,对于分配 1 的 justin,1+2 = 3),并且 Y 是它们的计划分配(例如,3--不是 6)。因此,3/3 = 1 *100 = 100% 已分配。
#custom function that works
get_cap_percent <- function (x, y) {
100*(x/y)
}
#Code that doesn't work
question %>%
dplyr::group_by(name) %>%
summarise_at(vars(contains("allocation_")), sum, na.rm = TRUE) %>%
summarise_at(vars(contains("allocation_")), get_cap_percent, x = ., y = scheduled_allocation)