Majid
Majid

Reputation: 14253

How to subtract two vectors' elements one by one?

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?

Upvotes: 1

Views: 1906

Answers (2)

David Arenburg
David Arenburg

Reputation: 92300

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

Upvotes: 1

Thomas
Thomas

Reputation: 44575

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

Upvotes: 2

Related Questions