gpt4 book ai didi

r - 添加一栏,根据学生的情况和剩余名额分配愿望

转载 作者:行者123 更新时间:2023-12-04 07:23:52 25 4
gpt4 key购买 nike

我想通过为每个学生(id)分配创建一个新列(UE),根据他们的分类(顺序)按照以下顺序(C1,C2,C3)选择教学单元(u1到u3)之一,而检查每个作业中每个教学单元的剩余名额(u1=最多 2 个名额,u2= 最多 2 个名额,u3 = 最多 3 个名额)。

    id<-c(11, 12, 13, 14, 15,16)
C1<-c("u1","u2","u2","u2","u1","u1")
C2<-c("u3","u3","u3","u3","u3","u2")
C3<-c("u2","u1","u1","u1","u2","na")
order<-c(1,2,3,4,5,6)

d = data.frame(id, C1, C2, C3, order)
正确答案在下面的示例文件中。
id     C1 C2 C3 Ordre UE
1 11 u1 u3 u2 1 u1
2 12 u2 u3 u1 2 u2
3 13 u2 u3 u1 3 u2
4 14 u2 u3 u1 4 u3
5 15 u1 u3 u2 5 u1
6 16 u1 u2 na 6 without allocation
但是,使用我的代码
d$UE <- ifelse(d$C1== "u1" & length(d$C1[d$C1=="u1"])<=2, 'u1',
ifelse(d$C1== "u2" & length(d$C1[d$C1=="u2"])<=2, 'u2',
ifelse(d$C1== "u3" & length(d$C1[d$C1=="u3"])<=3, 'u3',

ifelse(d$C2== "u1" & length(d$C2[d$C2=="u1"])<=2, 'u1',
ifelse(d$C2== "u2" & length(d$C2[d$C2=="u2"])<=2, 'u2',
ifelse(d$C2== "u3" & length(d$C2[d$C2=="u3"])<=3, 'u3',

ifelse(d$C2== "u1" & length(d$C2[d$C2=="u1"])<=2, 'u1',
ifelse(d$C2== "u2" & length(d$C2[d$C2=="u2"])<=2, 'u2',
ifelse(d$C2== "u3" & length(d$C2[d$C2=="u3"])<=3, 'u3',
'without allocation')))))))))
我得到
id C1 C2 C3 order                 UE
1 11 u1 u3 u2 1 without allocation
2 12 u2 u3 u1 2 without allocation
3 13 u2 u3 u1 3 without allocation
4 14 u2 u3 u1 4 without allocation
5 15 u1 u3 u2 5 without allocation
6 16 u1 u2 na 6 u2
我非常感谢你的帮助

最佳答案

您可以将最大数量的位置存储在一个单独的变量中,然后计算分配的位置:

# max places per unit
max_place <- c(u1 = 2, u2 = 2, u3 = 3)
# occupid places per unit
occ_place <- c(u1 = 0, u2 = 0, u3 = 0)

d$UE <- "without allocation"

# loop through your data.frame
for (i in seq_along(d)) {
# loop over choices
for (j in c("C1", "C2", "C3")) {
# check if there are places availble and allocate the unit
if (occ_place[d[i,j]] < max_place[d[i, j]] & !is.na(d[i,j]) & d[i,j] != "na") {
d$UE[i] <- d[i,j]
occ_place[d[i,j]] <- occ_place[d[i,j]] + 1
break
}
}
}
返回
  id C1 C2 C3 order                 UE
1 11 u1 u3 u2 1 u1
2 12 u2 u3 u1 2 u2
3 13 u2 u3 u1 3 u2
4 14 u2 u3 u1 4 u3
5 15 u1 u3 u2 5 u1
6 16 u1 u2 na 6 without allocation

关于r - 添加一栏,根据学生的情况和剩余名额分配愿望,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68328051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com