对于此示例,我将使用data.table
包。
假设你有一个教练表
coaches <- data.table(CoachID=c(1,2,3), CoachName=c("Bob","Sue","John"), NumPlayers=c(2,3,0))
coaches
CoachID CoachName NumPlayers
1: 1 Bob 2
2: 2 Sue 3
3: 3 John 0
和一个球员表
players <- data.table(PlayerID=c(1,2,3,4,5,6), PlayerName=c("Abe","Bart","Chad","Dalton","Egor","Frank"))
players
PlayerID PlayerName
1: 1 Abe
2: 2 Bart
3: 3 Chad
4: 4 Dalton
5: 5 Egor
6: 6 Frank
您希望将每位教练与一组球员匹配,以便
你好吗?
exampleResult <- data.table(CoachID=c(1,1,2,2,2,3), PlayerID=c(3,1,2,5,6,NA))
exampleResult
CoachID PlayerID
1: 1 3
2: 1 1
3: 2 2
4: 2 5
5: 2 6
6: 3 NA
答案 0 :(得分:6)
您可以在不更换玩家ID的情况下进行采样,获取所需的玩家总数:
set.seed(144)
(selections <- sample(players$PlayerID, sum(coaches$NumPlayers)))
# [1] 1 4 3 2 6
每个玩家都有相同的概率被包含在selections
中,并且该向量的排序是随机的。因此,您可以将这些球员分配到每个教练位置:
data.frame(CoachID=rep(coaches$CoachID, coaches$NumPlayers),
PlayerID=selections)
# CoachID PlayerID
# 1 1 1
# 2 1 4
# 3 2 3
# 4 2 2
# 5 2 6
如果您希望任何没有选择球员的教练拥有NA
值,您可以执行以下操作:
rbind(data.frame(CoachID=rep(coaches$CoachID, coaches$NumPlayers),
PlayerID=selections),
data.frame(CoachID=coaches$CoachID[coaches$NumPlayers==0],
PlayerID=rep(NA, sum(coaches$NumPlayers==0))))
# CoachID PlayerID
# 1 1 1
# 2 1 4
# 3 2 3
# 4 2 2
# 5 2 6
# 6 3 NA
答案 1 :(得分:5)
获取每一方的需求和供应,可以这么说:
demand <- with(coaches,rep(CoachID,NumPlayers))
supply <- players$PlayerID
然后我会......
randmatch <- function(demand,supply){
n_demand <- length(demand)
n_supply <- length(supply)
n_matches <- min(n_demand,n_supply)
if (n_demand >= n_supply)
data.frame(d=sample(demand,n_matches),s=supply)
else
data.frame(d=demand,s=sample(supply,n_matches))
}
示例:
set.seed(1)
randmatch(demand,supply) # some players unmatched, OP's example
randmatch(rep(1:3,1:3),1:4) # some coaches unmatched
我不确定这是OP想要覆盖的情况。
对于OP的期望输出......
m <- randmatch(demand,supply)
merge(m,coaches,by.x="d",by.y="CoachID",all=TRUE)
# d s CoachName NumPlayers
# 1 1 2 Bob 2
# 2 1 6 Bob 2
# 3 2 3 Sue 3
# 4 2 4 Sue 3
# 5 2 1 Sue 3
# 6 3 NA John 0
...类似地
merge(m,players,by.x="s",by.y="PlayerID",all=TRUE)
# s d PlayerName
# 1 1 2 Abe
# 2 2 1 Bart
# 3 3 2 Chad
# 4 4 2 Dalton
# 5 5 NA Egor
# 6 6 1 Frank
答案 2 :(得分:3)
这是使用简单的dplyr的答案。首先选择教练需要,然后对球员的需求进行抽样,最后将其全部结合起来。
library(dplyr)
set.seed(1234)
coach_needs <- coaches %>%
group_by( CoachID ) %>%
do( sample_n(., size=.$NumPlayers, replace=TRUE) ) %>%
select( -CoachID ) %>% ungroup()
player_needs <- players %>%
sample_n( size = nrow(coach_needs))
result <- cbind(coach_needs, player_needs)
result
这给了我:
CoachID CoachName NumPlayers PlayerID PlayerName
1: 1 Bob 2 4 Dalton
2: 1 Bob 2 1 Abe
3: 2 Sue 3 5 Egor
4: 2 Sue 3 2 Bart
5: 2 Sue 3 3 Chad
更新:如果NA
的教练需要NumPlayer == 0
,那么这是一个简单的单行:
result <- cbind(coach_needs, player_needs) %>%
rbind( coaches %>% filter(NumPlayers == 0), fill=TRUE )
result
给了我这个:
CoachID CoachName NumPlayers PlayerID PlayerName
1: 1 Bob 2 4 Dalton
2: 1 Bob 2 1 Abe
3: 2 Sue 3 5 Egor
4: 2 Sue 3 2 Bart
5: 2 Sue 3 3 Chad
6: 3 John 0 NA NA