R中ifelse语句的多个条件

时间:2015-04-14 21:03:39

标签: r rstudio data-manipulation

responses$Status有多种状态:Invited, Attended, Registered, Downloaded, Sent, Added

我尝试使用以下代码创建一个新的二进制列:

responses$hasresponded <- ifelse(responses$Status == c("Responded", "Attended", "Downloaded", "Contacted", "Requested"),1,0)

此代码运行,但它没有按照我的意愿执行。也就是说,代码1代表任何这些状态("Responded", "Attended", "Downloaded", "Contacted", "Requested"),其余为0。

1 个答案:

答案 0 :(得分:2)

%in%是你的朋友。

为了便于阅读而分拆:

OKresp <- c("Responded", "Attended", 
        "Downloaded", "Contacted", "Requested")
responses$hasresponded <- as.numeric(responses$Status %in% OKresp)

responses <- transform(responses,
          hasreponded = Status %in% OKresp)