R: string list in ifelse

浪子不回头ぞ 提交于 2021-02-05 06:51:28

问题


I am looking for something comparable to the "where 'var' in (...)" statement in MySQL.

My code is as follows:

data<-data.frame(id=10001:10030,cc1=rep(c("a","b","c"),10))
attach(data)
data$new<-ifelse(cc1=="a"|cc1=="b",1,0)

What is a better way to include a list of strings in the ifelse instead of using | ?

Something like: ifelse(cc1 in ('a','b'),1,0)

Many Thanks!


回答1:


ifelse(cc1 %in% c("a", "b"), 1, 0)

Or simply:

as.numeric(data$cc1 %in% c("a", "b"))

Avoid using attach though. It makes things messy.




回答2:


I'll just throw this one into the mix

> (!as.numeric(data$cc1) > 2)+0
## [1] 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0


来源:https://stackoverflow.com/questions/23617166/r-string-list-in-ifelse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!