What is the equivalent of Stata function inlist() in R?
I think you want %in%
:
statevec <- c("NC","AZ","TX","NY","MA","CA","NJ")state <- c("AZ","VT")state %in% statevec ## TRUE FALSEagevec <- c(16, 24, 45, 54, 67,74, 78, 79, 85) age <- c(34,45)age %in% agevec ## FALSE TRUE
edit: working on updated question.
Copying from @NickCox's link:
inlist(z,a,b,...) Domain: all reals or all strings Range: 0 or 1 Description: returns 1 if z is a member of the remaining arguments; otherwise, returns 0. All arguments must be reals or all must be strings. The number of arguments is between 2 and 255 for reals and between 2 and 10 for strings.
However, I'm not quite sure how this matches up with the original question. I don't know Stata well enough to know if z
can be a vector or not: it doesn't sound that way, in which case the original question (considering z=state
as a vector) doesn't make sense. If we consider that it can be a vector then the answer would be as.numeric(state %in% statevec)
-- I think.
Edit: Update by Ananda
Using your updated data, here's one approach, again using %in%
:
data <- data.frame(age=0:10)within(data, { m <- as.numeric(!age %in% c(1, 7, 9))}) age m1 0 12 1 03 2 14 3 15 4 16 5 17 6 18 7 09 8 110 9 011 10 1
This matches your expected output, by using !
(NOT) to invert the sense of %in%
. It seems to be a little backwards from the way I would think about it (normally, 0=FALSE
="is not in the list" and 1=TRUE
="is in the list") and my reading of Stata's definition, but if it's what you want ...
Or one can use ifelse
for more potential flexibility (i.e. values other than 0/1): substitute within(data, { m <- ifelse(age %in% c(1, 7, 9),0,1)})
in the code above.