IfElse 与 OR 运算符

Jeb*_*h15 1 r

试图将几个变量折叠成二分变量。我想使用 OR 运算符“|”根据原始变量中的条件值分配新值

数据框 c 有带有值的“原因”列:(“已回答”、“无法通话”、“已调用”、“未回答”、“语音邮件”)

# Collapse several responses into one value
c$answered <- if(c$reason == "answered"  | 
                     "couldNotTalk" |
                     "called_back") 
                    {c$answer == "answered"}
              else {c$unanswer == "not answered"}
Run Code Online (Sandbox Code Playgroud)

这不起作用,但以下是(即使效率不高):

"Answered" -> c$answer[c$reason == "answered"] 
"Answered" -> c$answer[c$reason == "couldNotTalk"]
"Answered" -> c$answer[c$reason == "called_back"]
Run Code Online (Sandbox Code Playgroud)

MrF*_*ick 5

在这种情况下,您可以使用%in%, 例如

c$reason %in% c("answered", "couldNotTalk", "called_back")
Run Code Online (Sandbox Code Playgroud)

然后要将其与值向量一起使用,而不是使用if,您可以使用称为 的矢量化版本ifelse()

c$answered <-  ifelse(
  c$reason %in% c("answered", "couldNotTalk", "called_back"),
  "answered",
  "not answered"
)
Run Code Online (Sandbox Code Playgroud)

或者当然你也可以