R 根据优先级分配资源
我想根据R 根据优先级分配资源,r,tidyverse,mutate,R,Tidyverse,Mutate,我想根据组的等级和限制创建分配列。 特别是,对于每个组,我都有一个优先级等级(例如,1,2,3或1,3,6或3,4,5等)。根据排名(小的数字是优先级),我想分配limit列中给出的资源。现在我用手做这件事。但是我想用tidyverse来表达这个练习。如何通过变异和分组(或其他方法)进行分配 使用tidyverse,分组后可以使用top\n。这将根据排名过滤顶部值,其中每个组中保留的n由限制确定。保留的数据将被指定为1,然后与原始数据合并 让我知道这是否提供了所需的结果 library(tidy
组
的等级
和限制
创建分配
列。
特别是,对于每个组,我都有一个优先级等级(例如,1,2,3或1,3,6或3,4,5等)。根据排名(小的数字是优先级),我想分配limit
列中给出的资源。现在我用手做这件事。但是我想用tidyverse
来表达这个练习。如何通过变异和分组(或其他方法)进行分配
使用tidyverse
,分组后可以使用top\n
。这将根据排名
过滤顶部值,其中每个组中保留的n由限制
确定。保留的数据将被指定为1,然后与原始数据合并
让我知道这是否提供了所需的结果
library(tidyverse)
df %>%
group_by(group) %>%
top_n(limit[1], desc(rank)) %>%
mutate(assign = 1) %>%
right_join(df) %>%
replace_na(list(assign = 0)) %>%
arrange(group, rank)
输出
group rank limit assign
<chr> <dbl> <dbl> <dbl>
1 A 1 1 1
2 A 2 1 0
3 A 3 1 0
4 B 1 1 1
5 B 3 1 0
6 B 6 1 0
7 C 3 2 1
8 C 4 2 1
9 C 5 2 0
10 C 6 2 0
组秩限制分配
一一
2 A 2 1 0
3 A 3 1 0
4b11
5B310
6b10
7 C 3 2 1
8C421
9C520
10C620
数据
df <- structure(list(group = c("A", "A", "A", "B", "B", "B", "C", "C",
"C", "C"), rank = c(1, 2, 3, 1, 3, 6, 3, 4, 5, 6), limit = c(1,
1, 1, 1, 1, 1, 2, 2, 2, 2)), class = "data.frame", row.names = c(NA,
-10L))
df