罗伊斯圈
我有以下有关学生成绩的数据集。
name <- c("John", "Rachel", "Judy", "James", "Oloo")
english <- c("70", "50e", "19c", "38^", "33^")
math <- c("65", "25c", "68", "32^", "50")
science <- c("45", "50", "25c", "27e", "72")
social <- c("56", "76", "42", "23^", "68")
marks <- data.frame(name, english, math, science, social)
marks要使学生通过考试,他们必须同时参加连续评估和期末考试,并在每门科目中至少取得40%的成绩。
Pass:学生在分数之后没有,没有,e或^,这意味着所有分数都在40分以上。
Supplementary:学生有^或e的地方。^意味着得分低于40分。有e的学生可能有超过40分,但仍然没有通过持续的评估。
special:学生有c,但没有e或^。
Supplementary and special:补充和特殊的结合。这意味着学生有e、^或两者兼有,同时也有c。
Discontinued:学生有4个或4个以上的e,4个或更多的^。此外,一个学生可能有一个组合的e和^发生4次或更多次。Task:对于每个学生(即一行数据),我希望在R中有一个代码,它将返回一个新列comment,如下所示。
name <- c("John", "Rachel", "Judy", "James", "Oloo")
english <- c("70", "50e", "19c", "38^", "33^")
math <- c("65", "25c", "68", "32^", "50")
science <- c("45", "50", "25c", "27^", "72")
social <- c("56", "76", "42", "23^", "68")
comment <- c("Pass", "Supplementary & Special", "Special", "Discontinued", "Supplementary")
marks_1 <- data.frame(name, english, math, science, social, comment)
marks_1再次注意:Pass:学生在分数之后没有、、e或^,这意味着所有分数都在40以上。
Supplementary:学生有^或e的地方。^意味着得分低于40分。有e的学生可能有超过40分,但仍然没有通过持续的评估。
special:学生有c,但没有e或^。
Supplementary and special:补充和特殊的结合。这意味着学生有e、^或两者兼有,同时也有c。
Discontinued:学生有4个或4个以上的e,4个或更多的^。此外,一个学生可能有一个组合的e和^发生4次或更多次。
发布于 2021-10-07 13:48:33
我认为您需要手动写下每条规则,并将它们应用于每一行。
library(dplyr)
apply_rules <- function(x) {
e_rule <- any(grepl('e', x, fixed = TRUE))
c_rule <- any(grepl('c', x, fixed = TRUE))
fail_rule <- any(grepl('^', x, fixed = TRUE))
case_when(all(grepl('[\\^e]', x)) ~ 'Discontinued',
(e_rule || fail_rule) && c_rule ~ 'Supplementary & Special',
fail_rule || e_rule ~ 'Supplementary',
c_rule && (c_rule || fail_rule) ~ 'Special',
!(e_rule || c_rule) ~ 'Pass',
fail_rule ~ 'Discontinued'
)
}
marks %>%
rowwise() %>%
mutate(comment = apply_rules(c_across(english:social)))
# name english math science social comment
# <chr> <chr> <chr> <chr> <chr> <chr>
#1 John 70 65 45 56 Pass
#2 Rachel 50e 25c 50 76 Supplementary & Special
#3 Judy 19c 68 25c 42 Special
#4 James 38^ 32^ 27^ 23^ Discontinued
#5 Oloo 33^ 50 72 68 Supplementary https://stackoverflow.com/questions/69478794
复制相似问题