2015-02-23 112 views
0

試圖將多個變量合併爲二分變量。我想使用OR運算符「|」來根據原始變量中的條件值分配新值,IfElse with OR運算符

數據幀c具有與值 「原因」 一欄( 「回答」, 「不能談」, 「called_back」, 「懸而未決」, 「語音郵件」)

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

這不是工作,但下面是(即使它是有效的):

"Answered" -> c$answer[c$reason == "answered"] 
"Answered" -> c$answer[c$reason == "couldNotTalk"] 
"Answered" -> c$answer[c$reason == "called_back"] 

回答

3

在這種情況下,而不是做一個或一堆的的,你可以使用%in%,爲例子

c$reason %in% c("answered", "couldNotTalk", "called_back") 

然後,爲了使用此值而不是使用if,您可以使用名爲ifelse()的矢量化版本。

c$answered <- ifelse(
    c$reason %in% c("answered", "couldNotTalk", "called_back"), 
    "answered", 
    "not answered" 
) 

或當然你也可以

+0

感謝。第二個是我想要做的,所以是完美的。 – Jebediah15 2015-02-23 17:58:29