How to compare two columns and write the result into a third - using R
You are not using ifelse in a correct fashion:
ifelse(test_expression,x,y)
Here, test_expression must be a logical vector (or an object that can be coerced to logical). The return value is a vector with the same length as test_expression.
This returned vector has element from x if the corresponding value of test_expression is TRUE or from y if the corresponding value of test_expression is FALSE.You should not try to assign the value inside ifelse
here, rather entire ifelse
should be assigned to a new object entirely.
goals$winner <- ifelse(goals$x1 > goals$x2, "h", ifelse(goals$x1 < goals$x2, "d", "a"))
Search for ?ifelse
in R console for better understanding.
You can avoid ifelse
statement with subsetting:
df <- data.frame(x1 = c(1,4,0,2,1,1,1,0),x2=c(1,0,0,1,1,1,1,0))
df$winner <- NULL
df[df$x1 > df$x2,"winner"] <- "h"
df[df$x1 < df$x2,"winner"] <- "d"
df[df$x1 == df$x2,"winner"] <- "a"
Answer:
df
x1 x2 winner
1 1 1 a
2 4 0 h
3 0 0 a
4 2 1 h
5 1 1 a
6 1 1 a
7 1 1 a
8 0 0 a
>
Related videos on Youtube
JohnnyS
Updated on June 04, 2022Comments
-
JohnnyS almost 2 years
X1 is the column of the home team.
goals X1 X2 1 1 1 2 4 0 3 0 0 4 2 1 5 1 1 6 1 1 7 1 1 8 0 0 ...
If I type the nested elseif, I get the correct result in the console.
> ifelse(goals$X1 > goals$X2, goals$winner <- "h",ifelse(goals$X1 < goals$X2, goals$winner <- "d",goals$winner <- "a")) [1] "a" "h" "a" "h" "a" "a" "a" "a" "h" "h" "h" "h" "h" "a" "h" "a" "a" "h" [19] "h" "a" "h" "h" "h" "d" "h" "h" "h" "h" "a" "a" "a" "d" "d" "h" "d" "h" [37] "h" "h" "a" "a" "h" "h" "a" "h" "h" "h" "h" "h" "h" "h" "a" "h" "h" "h" [55] "h" "a" "h" "h" "h" "h" "h" "a" "h" "h" "h" "h" "d" "h" "h" "a" "h" "a" [73] "d" "h" "d" "h" "h" "h" "h" "h" "h" "a" "d" "h" "d" "h" "d" "d" "d" "a" [91] "h" "h" "h" "d" "a" "h" "h" "h" "h" "h" "h" "h" "d" "h" "h" "a" "d" "h" [109] "h" "a" "d" "h" "h" "h" "h" "h" "a" "d" "d" "h" "h" "h" "h" "h" "h" "h" [127] "h" "a" "h" "h" "h" "h" "h" "a" "h" "a"
However, if I check the data frame it's not correct because I have only 'a''s.
> goals X1 X2 winner 1 1 1 a 2 4 0 a 3 0 0 a 4 2 1 a 5 1 1 a 6 1 1 a 7 1 1 a 8 0 0 a ...
Where am I wrong?
-
Ronak Shah about 7 years
goals$winner <- ifelse(goals$X1 > goals$X2, "h", ifelse(goals$X1 < goals$X2, "d", "a"))
-
JohnnyS about 7 yearsThanks that solved it. Together with Kabirs explanation I was able to learn a lot!
-