如何在R中使用或在ifelse语句中?

时间:2019-01-12 16:19:10

标签: r

我正在使用下面的代码,它不起作用。Y有2个级别(or函数不起作用)。解决方案是什么?

data$Team1=factor(data$Team1)

y=levels(data$Team1)

data$win_loss=ifelse(data$winner==y[2]|y[1], "winner",
              ifelse(data$winner==is.na(data$winner),"noresult","looser"))

样本数据 Team1冠军赢/输 x1 x1 x1 x1 x1 x1 x2 x3 x3 x1 x1 x1 x1 x4 x4 x1 x1 x1 x1不适用 x1 NA NA

我想要基于Team1和获胜者的赢/输栏。

2 个答案:

答案 0 :(得分:0)

您可以分两步进行操作,使其保持简单:

# replace NA
data$Team1[is.na(data$Team1)] <- 'noresult'

# replace other values
data$Team1 <- ifelse(data$Team1 %in% levels(data$Team1), 'winner', 'loser')

答案 1 :(得分:0)

选项1

在“或”操作的另一端使用data$winner

data$Team1=factor(data$Team1)

y=levels(data$Team1)

data$win_loss=ifelse(data$winner==y[2] | data$winner==y[1], "winner",
              ifelse(is.na(data$winner),"noresult","loser"))

选项2

调用向量y[1:2]并使用%in%运算符。

data$Team1=factor(data$Team1)

y=levels(data$Team1)

data$win_loss=ifelse(data$winner %in% y[1:2], "winner",
              ifelse(is.na(data$winner),"noresult","loser"))