R Question: ifelse producing unexpected results
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.
Examp开发者_如何学编程le:
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$Value
is 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.
I have no idea, because when I run this on my machine I get the right answer:
> print(example)
Question StudentID SchoolID Value Worth Answer Points
1 18 101290 84386 2 2 Co 0
2 18 100878 84386 2 2 Co 0
3 18 100895 84386 1 5 Co 0
4 18 100913 84386 2 2 Co 0
5 18 100884 84386 2 2 Co 0
>
> example$Points <- ifelse(example$Answer == "Co", example$Value, example$Points)
>
> print(example)
Question StudentID SchoolID Value Worth Answer Points
1 18 101290 84386 2 2 Co 2
2 18 100878 84386 2 2 Co 2
3 18 100895 84386 1 5 Co 1
4 18 100913 84386 2 2 Co 2
5 18 100884 84386 2 2 Co 2
Here's the code that I'm using:
example = read.table('data.txt', header = T)
print(example)
example$Points <- ifelse(example$Answer == "Co", example$Value, example$Points)
print(example)
Here's data.txt:
Question StudentID SchoolID Value Worth Answer Points
18 101290 84386 2 2 Co 0
18 100878 84386 2 2 Co 0
18 100895 84386 1 5 Co 0
18 100913 84386 2 2 Co 0
18 100884 84386 2 2 Co 0
Hopefully this helps. What happens when you print out the type of example$Value? Try this:
print( typeof(example$Value) )
[1] "integer"
If that comes out as a factor, then that might explain your odd results.
精彩评论