Match 2 tables in R

0

Good afternoon,

I wanted to know what function I should take to be able to relate in R two tables (table 1, in which I have all my raw data of my species and table 2, in which I have an index with representative species). The idea is to add a value (1 for example) to the species in table 1 that also appear in table 2 and another value (0 for example) to those species that appear in table 1 but not in table 2.

Thanks in advance. Greetings.

    
asked by Adrián P.L. 10.10.2017 в 17:59
source

1 answer

0

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
    
answered by 11.10.2017 / 04:46
source