Create data…
1 2 3 4 5 6 7 |
Name <- c("John", "Max", "Nancy", "Paul", "Sandra") Major <- c("English", "Medicine", "Physics", "Chemistry", "Biology") Grade <- c("A","B","C","D","F") data <- data.frame(Name, Major, Grade) data |
1 2 3 4 5 6 7 |
> data Name Major Grade 1 John English A 2 Max Medicine B 3 Nancy Physics C 4 Paul Chemistry D 5 Sandra Biology F |
Given that an A equals to 4, a B equals to 3 and so on, we can use ifelse() to extract a numeric grade as follows…
1 2 3 4 5 6 7 8 |
attach(data) data$Grade_Numeric <- ifelse(Grade == "A", 4, ifelse(Grade == "B", 3, ifelse(Grade == "C", 2, ifelse(Grade == "D", 1,0)))) detach(data) data |
1 2 3 4 5 6 7 |
> data Name Major Grade Grade_Numeric 1 John English A 4 2 Max Medicine B 3 3 Nancy Physics C 2 4 Paul Chemistry D 1 5 Sandra Biology F 0 |
How ifelse() commands works is very straightforward. The first argument is the logical test, the second argument if the value if true, the third argument if value if false. For example, ifelse(Grade == “A”, 4 means if Grade equals to A, then the value if 4. As you can see, the third argument is another ifelse() to test if the grade is a B and so on.