我有一列学生姓名,一列是每个学生的团体编号。我该如何随机分配每个学生担任另一个小组的工作的裁判,有人可以让我知道如何构建功能来解决该问题吗?他们不能成为自己小组的法官。
Bob Ross 1
Kanye West 1
Chris Evans 1
Robert Jr 1
Bruce Wayne 2
Peter Parker 2
Steven Strange 2
Danny rand 2
Daniel Fisher 2
Rob Son 3
Son Bob 3
Chun Li 3
Ching Do 3
Ping Pong 3
Michael Jackson 4
Rich Brian 4
Ryan Gosling 4
Nathan Nguyen 4
Justin Bieber 4
答案 0 :(得分:2)
这是使用tidyverse
方法的一种方法。基本上,这表示对于map_int
中的每个值(group
),从不是当前值的组中选取sample
。
library(tidyverse)
df <- structure(list(name = c("Kanye West", "Chris Evans", "Robert Jr", "Bruce Wayne", "Peter Parker", "Steven Strange", "Danny rand", "Daniel Fisher", "Rob Son", "Son Bob", "Chun Li", "Ching Do", "Ping Pong", "Michael Jackson", "Rich Brian", "Ryan Gosling", "Nathan Nguyen", "Justin Bieber"), group = c(1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -18L))
df %>%
mutate(
to_judge = map_int(
.x = group,
.f = ~ sample(
x = unique(group)[unique(group) != .x],
size = 1
)
)
)
#> # A tibble: 18 x 3
#> name group to_judge
#> <chr> <int> <int>
#> 1 Kanye West 1 4
#> 2 Chris Evans 1 2
#> 3 Robert Jr 1 3
#> 4 Bruce Wayne 2 1
#> 5 Peter Parker 2 3
#> 6 Steven Strange 2 3
#> 7 Danny rand 2 4
#> 8 Daniel Fisher 2 1
#> 9 Rob Son 3 1
#> 10 Son Bob 3 2
#> 11 Chun Li 3 4
#> 12 Ching Do 3 4
#> 13 Ping Pong 3 4
#> 14 Michael Jackson 4 2
#> 15 Rich Brian 4 3
#> 16 Ryan Gosling 4 1
#> 17 Nathan Nguyen 4 2
#> 18 Justin Bieber 4 1
由reprex package(v0.2.0)于2018-09-20创建。
答案 1 :(得分:1)
tidyverse
的另一种选择是在group_by
列中group
,用setdiff
定义样本矢量,并绘制成组大小的样本:>
df <- data.frame(Student = LETTERS[1:20],
Group = gl(4, 5))
library(tidyverse)
df %>%
group_by(Group) %>%
mutate(Judge = sample(setdiff(unique(df$Group), Group), n(), replace = T))
# A tibble: 20 x 3
# Groups: Group [4]
Student Group Judge
<fct> <fct> <chr>
1 A 1 4
2 B 1 2
3 C 1 3
4 D 1 3
5 E 1 4
6 F 2 4
7 G 2 4
8 H 2 1
9 I 2 1
10 J 2 4
11 K 3 4
12 L 3 2
13 M 3 1
14 N 3 2
15 O 3 2
16 P 4 2
17 Q 4 1
18 R 4 2
19 S 4 1
20 T 4 3