R: Remove the number of occurrences of values in o

2020-04-16 17:26发布

问题:

Apologies for the confusing title, but I don't know how to express my problem otherwise. In R, I have the following problem which I want to solve:

x <- seq(1,1, length.out=10)
y <- seq(0,0, length.out=10)
z <- c(x, y)
p <- c(1,0,1,1,0,0)

How can I remove vector p from vector z so that vector a new vector i now has three occurrences of 1 and three occurrences 0 less, so what do I have to do to arrive at the following result? In the solution, the order of 1's and 0's in z should not matter, they just might have been in a random order, plus there can be other numbers involved as well.

i
> 1 1 1 1 1 1 1 0 0 0 0 0 0 0

Thanks in advance!

回答1:

Similar to @VincentGuillemot's answer, but in functional programming style. Uses purrr package:

i <- z
map(p, function(x) { i <<- i[-min(which(i == x))]})
i

> i
 [1] 1 1 1 1 1 1 1 0 0 0 0 0 0 0


回答2:

There might be numerous better ways to do it:

i <- z
for (val in p) {
  if (val %in% i) {
    i <- i[ - which(i==val)[1] ]
  }
}

Another solution that I like better because it does not require a test (and thanks fo @Franck's suggestion):

for (val in p) 
  i <- i[ - match(val, i, nomatch = integer(0) ) ]


标签: r vector