开发者

Binary Grouping in R

开发者 https://www.devze.com 2023-01-06 14:37 出处:网络
Suppose I have two vectors of same dimensions: x <-c(0.49534,0.80796,0.93970,0.99998) co开发者_如何学编程unt<-c(0,33,0,4)

Suppose I have two vectors of same dimensions:

x <-c(0.49534,0.80796,0.93970,0.99998)
co开发者_如何学编程unt      <-c(0,33,0,4)

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

  1. Vector grzero that contain value in x with count value greater than 0 and
  2. Vector eqzero with value in x with count value equal to zero.

Yielding

> print(grzero)
> [1] 0.80796 0.99998
> print(eqzero)
> [1] 0.49534 0.93970


grzero <- x[count > 0]
eqzero <- x[count == 0]

Why this works is because expressions like count > 0 evaluate to a vector of Booleans, so count > 0 is FALSE TRUE FALSE TRUE and count == 0 is TRUE FALSE TRUE FALSE. Then you index vector x with Boolean vector and get only those elements for which corresponding value of Boolean vector is TRUE.


split may be useful,

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

this is a bad hack though...

0

精彩评论

暂无评论...
验证码 换一张
取 消