Similarity of elements in different vectors

Asked

Viewed 84 times

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 from B and not the position.

I thought this would work:

B[mm] 

But it didn’t. How do I do it?

  • Is that R? format code, put language tags, will help your question get more visibility

  • Yeah, thanks for the tip.

  • nothing, just give up there xD

1 answer

3


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

B[unlist(mm)]

that the result will be the desired:

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

If you want to get the unique results without repetition, do

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.