首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在R中遍历几行数据

在R中遍历几行数据
EN

Stack Overflow用户
提问于 2021-10-07 09:34:24
回答 1查看 80关注 0票数 1

罗伊斯圈

我有以下有关学生成绩的数据集。

代码语言:javascript
复制
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,如下所示。

代码语言:javascript
复制
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次或更多次。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-07 13:48:33

我认为您需要手动写下每条规则,并将它们应用于每一行。

代码语言:javascript
复制
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         
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69478794

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档