Home > Software engineering >  For Loop with If/Else to create a new column in a df
For Loop with If/Else to create a new column in a df

Time:11-24

I'm student trying to learn R... and have spent hours trying to figure this out but have so far failed. maybe I'm going about it the wrong way, or don't know something basic.

I have data with student number, and module results - the results are in numeric form, and I want to change the result to the grade - A, B, C etc. I have managed to create a loop that will print the grade but can't figure out how to put it in the dataframe.

The dataset I have is quite big, so I have created some dummy data for the example below, the code runs, and doesn't give me any errors but it doesn't replace the number with the letter grade:

`Result <- c(50,67,89,77,65,66,70,73,69,80)

    for (i in Result){
if (i < 16.67) {
print ("G ")
i <- "G "
} else if (i < 26.67) {
print ("F ")
 i <- "F "
} else if (i < 36.67) {
print ("E ")
i <- "E "
} else if (i < 40) {
print ("D-")
i <- "D "
}else if (i < 43.33) {
 print ("D")
 i <- "D"
}else if (i < 46.67) {
print ("D ")
i <- "D " 
}else if (i < 50) {
print ("C-")
i <- "C-"
}else if (i < 53.33) {
print ("D")
i <- "D"
}else if (i < 56.67) {
print ("D ")
i <- "D "
}else if (i < 60) {
print ("B-")
i <- "B-"
}else if (i < 63.33) {
print ("B")
i <- "B"
}else if (i < 66.67) {
print ("B ")
i <- "B "
}else if (i < 70) {
print ("A-")
i <- "A-"
}else if (i < 73.33) {
print ("A")
i <- "A"
}else if (i < 100) {
print ("A ")
i <- "A "
}
}

# result: [1] "D"
[1] "A-"
[1] "A "
[1] "A "
[1] "B "
[1] "B "
[1] "A"
[1] "A"
[1] "A-"
[1] "A "`   `


    

Any advice would be greatly appreciated. many thanks, El.

CodePudding user response:

Put your example data in a data.frame:

df <- data.frame( result = c(50,67,89,77,65,66,70,73,69,80) )

Then use cut() to get the grades in a new column of that data.frame:

df$grade <- cut(df$result, 
            breaks = c(0, 16.67, 26.67, 36.67, 40, 43.33, 46.67, 50, 53.33, 56.67, 60, 63.33, 66.67, 70, 73.33, 100), 
            labels = c("G ", "F ", "E ", "D-", "D", "D ", "C-", "C", "C ", "B-", "B", "B ", "A-", "A", "A "))

Print the result to check:

df

   result grade
1      50    C-
2      67    A-
3      89    A 
4      77    A 
5      65    B 
6      66    B 
7      70    A-
8      73     A
9      69    A-
10     80    A 

Notice that (1) it's better to save the results into a data.frame than to simply print them, and (2) many things can be done better/quicker in R if you don't loop; instead use R's vectorized functions (like cut!).

  • Related