Adrian, you have not indicated what type of object you speak when you mention "a table", I imagine that it is a data.frame
, it is also good that you pose the question with some example. Let's see how you can solve what you pose:
tabla1 <- data.frame(especie = c("perro", "gato", "ratón"))
tabla2 <- data.frame(especie = c("vaca", "buitre", "perro", "ratón"))
We have two data.frame
and we want to add a column to tabla1
that tells us if the species is in tabla1
, we can solve it like this:
tabla1$EstaEnTabla2 <- ifelse(is.na(match(tabla1$especie, tabla2$especie)),0,1)
First of all we used match()
that we returns a vector with the first occurrence of tabla1$especie
in tabla2$especie
and NA
in case there are no matches. Finally, we use the ternary function ifelse()
with < a href="http://stat.ethz.ch/R-manual/R-devel/library/base/html/NA.html"> is.na()
to return 0 if match
is a value NA
and 1
otherwise. With this simple basic functions we end up with a data.frame
like this:
especie EstaEnTabla2
1 perro 1
2 gato 0
3 ratón 1