作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想通过为每个学生(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/
我正在为 friend 写一个页面,人们可以在其中预订类(class)。所有类(class)名额有限。 在 PHP 页面上,我将获取类(class)的空闲时段(从 mysql),检查是否有足够的空间用
我是一名优秀的程序员,十分优秀!