What is equivalent to the SQL IN keyword in R?

In SQL, you can easily avoid several OR conditions if you are looking for many values ​​of a specific variable (column) using IN. For instance:

SELECT * FROM colors WHERE color in ('Red', 'Blue', 'Green')

How do I do this in R? Currently, I have to do it as follows:

shortlisted_colors <- subset(colors, color == 'Red' | color == 'Blue' | color == 'Green')

What's better?

+4
source share
2 answers
shortlisted_colors <- subset(colors, color %in% c('Red', 'Blue', 'Green'))
+9
source

I suppose it might be hard to find "in", but the answer is "% in%". The search can also be difficult because it inis a reserved word in R due to its use in the iterator specification in for-loops:

subset(colors, color %in% c('Red' ,'Blue','Green') )

Cm:

?match
?'%in%'   # since you need to quote names with special symbols in them

"%" - , , @hadley dplyr -package. SQL, , , dplyr . , dplyr - SQL .

+2

All Articles