1

I have these two vectors:

first<-c(1,2,2,2,3,3,4)
second<-c(1,2)

now I want first without second elements to get result like this:(2,2,3,3,4); indeed, I don't want all 2s removed and only want one by one subtracting.

I have tried this (from here):

'%nin%' <- Negate('%in%')
first<-first[first %nin% second]

but it removes all 2s from first and gives this result: (3,3,4)

How can I do that?

Community
  • 1
  • 1
Majid
  • 13,853
  • 15
  • 77
  • 113
  • @rawr just the first one! as I said, one by one; does `first[-second]` do one by one? – Majid Nov 09 '14 at 20:17
  • I'm confused if `second` should be indices of `first` that you want to remove or a specific pattern of elements from `first` that should be removed. – rawr Nov 09 '14 at 20:24
  • @rawr more generic example: let `first` be `(1,2,4,2,3,1,2,3)` and `second` be `(9,2,2,1)`. in this case, intersections are `(2,2,3)`. so two 2 and one 3 should be removed from `first`. – Majid Nov 09 '14 at 20:32

2 Answers2

2

Try this:

first[-sapply(second, function(x) head(which(is.element(el=first, x)), 1))]
## [1] 2 2 3 3 4

This won't work if you have duplicate elements in second. In that case, I think you'll need a loop:

first2 <- first
for(i in seq_along(second)) {
    first2 <- first2[-head(which(is.element(el=first2, second[i])), 1)]
}
first2
# [1] 2 2 3 3 4

first2 <- first
second <- c(1,2,2)
for(i in seq_along(second)) {
    first2 <- first2[-head(which(is.element(el=first2, second[i])), 1)]
}
first2
## [1] 2 3 3 4
Thomas
  • 43,637
  • 12
  • 109
  • 140
1

How about

second<-c(1, 2)
first[-match(second, first)]
## [1] 2 2 3 3 4

For a more complected cases, here's an option using <<-

second <- c(1, 2, 2)
invisible(lapply(second, function(x) first <<- first[-match(x, first)]))
first
## [1] 2 3 3 4
David Arenburg
  • 91,361
  • 17
  • 137
  • 196