Question

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!

Était-ce utile?

La solution

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.

Autres conseils

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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top