R: Remove the number of occurrences of values in o

2020-04-16 17:42发布

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!

标签: r vector
2条回答
三岁会撩人
2楼-- · 2020-04-16 17:43

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
查看更多
够拽才男人
3楼-- · 2020-04-16 17:50

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) ) ]
查看更多
登录 后发表回答