Binary Grouping in R

Suppose I have two vectors of the same size:

x <-c(0.49534,0.80796,0.93970,0.99998)
count      <-c(0,33,0,4)

How can I group the "x" vectors into two vectors:

  • A vector grzerocontaining a value in x with a countvalue greater than 0 and
  • A vector eqzerowith a value in x with a countvalue of zero.

Yielding

> print(grzero)
> [1] 0.80796 0.99998
> print(eqzero)
> [1] 0.49534 0.93970
+3
source share
2 answers
grzero <- x[count > 0]
eqzero <- x[count == 0]

Why does this work, because expressions like this count > 0are evaluated by a vector of logical elements, therefore count > 0- FALSE TRUE FALSE TRUEand count == 0- TRUE FALSE TRUE FALSE. Then you index the vector xwith the Boolean vector and get only those elements for which the corresponding value of the Boolean vector TRUE.

+17

,

split(x,c("eqzero","grzero")[(count>0)+1])

, ...

+2

Source: https://habr.com/ru/post/1753251/


All Articles