1

I want to identify which values in one vector are present in another vector. Sometimes, in my application, none of the values of the first vector are present; in such cases I would like NA. My current approach returns integer(0) when this occurs:

l <- 1:3
m <- 2:5
n <- 4:6
l[l %in% m]

1] 2 3

l[l %in% n]

integer(0)

This post discusses how to capture integer(0) using length, but is there a way to avoid integer(0) in the first place, and do this operation in just one step? Answers to the previous question suggest that any could be used but I fail to see how that would work in this example.

tvg
  • 388
  • 2
  • 13

2 Answers2

2

You could catch the integer(0) with a custom function:

l <- 1:3
m <- 2:5
n <- 4:6

returnsafe <- function(a, b) {
    result <- a[a %in% b]
    if(is.integer(result) && length(result) == 0L) {
        return(NA)
    } else {
        return(result)
    }
}


> returnsafe(l, n)
[1] NA
DSGym
  • 2,807
  • 1
  • 6
  • 18
1

You can do:

l[match(l, n)]

[1] NA NA NA

Or:

any(l[match(l, n)])

[1] NA
tmfmnk
  • 38,881
  • 4
  • 47
  • 67