In a toy problem of mine, I have a vector a
made of integers and I want to efficiently remove from a
terms that are also in a vector b
. I wrote the code
newa=NULL
for (j in 1:length(a))
if (min(abs(a[i]-b))>0) newa=c(newa,a[i])
but this is terrible...
You could just use intersect
, setdiff
, etc (see ?setdiff
):
a <- 1:10
b <- c(2, 3, 5, 7)
setdiff(a, b)
# [1] 1 4 6 8 9 10
Or even just use %in%
:
a[!(a %in% b)] # (a %in% b) is TRUE in index i if a[i] is in b.
It's lightening fingers like mathematical.coffee that make it so I never get to answer questions :P
I do this a lot using %in%. And I nabbed a great little bit of code from Stephen Turner that makes it even easier!
## Returns a logical vector TRUE for elements of X not in Y
"%nin%" <- function(x, y) !(x %in% y)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.