Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create new column using data from If Else Loop in R

I have data frame that consist of names and scores of certain individual

       name  score
0       Ted     90
1   Rebecca     88
2       Roy     78
3    Leslie     85
4    Nathan     75
5     Jamie     70
6       Sam     78
7     Isaac     70
8    Keeley     85
9     Beard     90
10    Colin     70
11     Will     70
12      Jan     82
13  Richard     70

I want to add new column called verdict that contain their degree based on their score. I used loping to do that with hope that the result would be like this

       name  score               verdict
0       Ted     90     Passed, Cum Laude
1   Rebecca     88     Passed, Cum Laude
2       Roy     78          Passed, Good
3    Leslie     85     Passed, Cum Laude
4    Nathan     75          Passed, Good
5     Jamie     70          Passed, Good
6       Sam     78          Passed, Good
7     Isaac     70          Passed, Good 
8    Keeley     85     Passed, Cum Laude
9     Beard     90     Passed, Cum Laude
10    Colin     70          Passed, Good
11     Will     70          Passed, Good
12      Jan     82     Passed, Excellent
13  Richard     70          Passed, Good

I’m using this code below to do that, but nothing happened. The new column didnt exist and there is no error or warning message in R console

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df$verdict <-
  for (score in df$score){
    if (score >= 85)
      return('Passed, Cum Laude')
    else if (score < 85 & score >= 80)
      return('Passed, Excellent')
    else if (score < 80 & score >= 70)
      return('Passed, Good')
    else if (score < 70 & score >= 60)
      return('Passed')
    else
      return('Not Passed')
}

>Solution :

The if statement in R is not vectorized, and you would instead want to use ifelse. In this case, the case_when() function from the dplyr library is a good fit for your requirement:

df$verdict <- case_when(
    df$score >= 85 ~ "Passed, Cum Laude",
    df$score >= 80 ~ "Passed, Excellent",
    df$score >= 70 ~ "Passed, Good",
    df$score >= 60 ~ "Passed",
    TRUE ~ "Not Passed"
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading