I am new to R and am getting unexpected results while using the ifelse() function. Here is an example. Below is a subset of the data frame I am working with. After the last command, why does the example$Points column contain 12 instead of 2? I have tried this for many different values of example$Value and the result is always 10 more than what I expect.
Example:
example
Question StudentID SchoolID Value Worth Answer Points
2926 18 101290 84386 2 2 Co 0
2927 18 100878 84386 2 2 Co 0
2928 18 100895 84386 1 5 Co 0
2929 18 100913 84386 2 2 Co 0
2930 18 100884 84386 2 2 Co 0
example$Points <- ifelse(example$Answer == "Co", example$Value, example$Points)
example
Question StudentID SchoolID Value Worth Answer Points
2926 18 101290 84386 2 2 Co 12
2927 18 100878 84386 2 2 Co 12
2928 18 100895 84386 1 5 Co 11
2929 18 100913 84386 2 2 Co 12
2930 18 100884 84386 2 2 Co 12
I’ve been using the work-around of just then subtracting 10 from the column, but I would like to avoid this and get to the bottom of what is going on here.
Any help would be greatly appreciated. Thank you!
My guess is that
example$Valueis a factor and you’re getting the underlying codes instead of the labels. I recommend taking a look at your data as soon as it’s read into R to see what’s causing your input method to treat those values as factors instead of integer / numeric.