如何比较两列并将结果写入第三列 - 使用R

时间:2017-04-06 17:24:10

标签: r dataframe

X1是主队的专栏。

  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
...

如果我输入嵌套的elseif,我会在控制台中得到正确的结果。

> 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"

但是,如果我检查数据框是不正确的,因为我只有'a'。

> 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
...

我哪里错了?

2 个答案:

答案 0 :(得分:0)

您的问题出现是因为您更新了ifelse中的获胜者列。要做你想做的事:

goals$winner <-ifelse(goals$X1 > goals$X2,  "h",ifelse(goals$X1 < goals$X2, "d", "a"))

答案 1 :(得分:0)

您没有以正确的方式使用ifelse:

ifelse(test_expression,x,y)

这里,test_expression必须是逻辑向量(或可以强制转换为逻辑的对象)。返回值是一个与test_expression具有相同长度的向量。

如果test_expression的对应值为TRUE,则返回的向量具有x中的元素;如果test_expression的对应值为FALSE,则返回y中的元素。您不应该尝试在此处ifelse内分配值,而是整个{{ 1}}应该完全分配给一个新对象。

ifelse

在R控制台中搜索goals$winner <- ifelse(goals$x1 > goals$x2, "h", ifelse(goals$x1 < goals$x2, "d", "a")) 以便更好地理解。

您可以通过子集化来避免?ifelse语句:

ifelse

答案:

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"