Similarity of elements in different vectors

3

I have two vectors:

A <- c("RS", "DF", "CE")
B <- c("Porto Alegre - RS", "Brasília - DF", "Fortaleza - CE", "Porto Alegre - RS", 
"Acre - AC", "Recife - PE")

and a function:

f <- function(a,b) {
  lista <- grep(a,b, fixed = FALSE)
  return(lista)
}
mm <- lapply(A, B, FUN = f)

I'm getting the position of the elements from A to B, but I need the elements of B, not the position.

I thought this would work:

B[mm] 

But it did not. How do I do this?

    
asked by anonymous 20.01.2017 / 20:36

1 answer

3

The result of lapply(A, B, FUN = f) is a list. Rode

B[unlist(mm)]

the result will be as desired:

[1] "Porto Alegre - RS" "Porto Alegre - RS" "Brasília - DF"    
[4] "Fortaleza - CE"

If you want to get the results unrepeatable, do

unique(B[unlist(mm)])
[1] "Porto Alegre - RS" "Brasília - DF"     "Fortaleza - CE" 
    
24.01.2017 / 21:15