Is there a function similar to MATLAB's ismember in R?

Is there ONE function in R which gives out a similar output to MATLAB's ismember() if I want a logical array and the indexes of locations where the array elements are members of set array.

Matlab code:

A = [5 3 4 2]; B = [2 4 4 4 6 8]; [la loc] = ismember(A,B) 

Output:

la = 1x4 logical array 0 0 1 1 loc = 0 0 2 1 

To get a similar output in R right now I use this:

ismember <- function(A,B){ out <- match(A,B) out <- cbind(out,(A %in% B)*1) out[is.na(out)] <- 0 } ismember(A,B) 

Output:

 out [1,] 0 0 [2,] 0 0 [3,] 2 1 [4,] 1 1 
3

1 Answer

The Matlab function ismember can be translated to R in two ways:

  • is.element
  • %in%

hence:

ismember(A,B) ---> is.element(A, B) ismember(A,B) ---> A %in% B 

If you want to include indexing, you can use the match function:

loc <- match(A, B) print(loc) [1] NA NA 2 1 

By default, when using match, values with no match return NA but you can change this behavior through the nomatch parameter:

loc <- match(A, B, nomatch = 0) print(loc) [1] 0 0 2 1 

In conclusion, your Matlab code:

A = [5 3 4 2]; B = [2 4 4 4 6 8]; [la,loc] = ismember(A,B); 

can basically be translated to:

A <- c(5,3,4,2) B <- c(2,4,4,4,6,8) la <- is.element(A, B) loc <- match(A, B, nomatch = 0) 

If you want to obtain both values combined into a single variable you could use:

res <- cbind.data.frame(la = is.element(A, B), loc = match(A, B, nomatch = 0)) print(res$la) [1] FALSE FALSE TRUE TRUE print(res$loc) [1] 0 0 2 1 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like