Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify what are the exact elements of a vector?

I have a vector x of the form:

x=c(601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614,
 615, 616, 617, 618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 630,
 631, 632, 633, 634, 635, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646,
 647, 648, 649, 650)

If length (x) == 50: I would like to test (TRUE or FALSE) if x is exactly equal to one of the intervals 1:50 or 51:100 or 101:150 or 151:200 .... or 951:1000.

Or if length (x)> 50, I would like to test (TRUE or FALSE) if x is exactly equal to the union of intervals composed by ((1:50 U 51: 100) or (1:50 U 101: 150) or (51 : 100 U 151: 200) ....).

My attempt:

all(
    x == c(1:50) | 
    x == c(51:100) | 
    x == c(101:150) | 
    x == c(151:200) | 
    x == c(201:250) | 
    x == c(251:300) | 
    x == c(301:350) | 
    x == c(351:400) | 
    x == c(401:450) | 
    x == c(451:500) | 
    x == c(501:550) | 
    x == c(551:600) | 
    x == c(601:650) | 
    x == c(651:700) | 
    x == c(701:750) | 
    x == c(751:800) | 
    x == c(801:850) | 
    x == c(851:900) | 
    x == c(901:950) | 
    x == c(951:1000)
)

I would like to optimize this code.

PS: I'm not trying to have a frequency table of the x elements and intervals like this question. I want to know if x corresponds exactly to one or the union of those intervals.

like image 224
Ph.D.Student Avatar asked Dec 31 '22 15:12

Ph.D.Student


2 Answers

You can use cut, i.e.

unique(cut(x, breaks = seq(0, 1000, by = 50)))
#[1] (600,650]

If you want a boolean If x is included in one those intervals, then you can do,

unique(cut(x, breaks = seq(0, 1000, by = 50))) != ''
#[1] TRUE

#or If you only want to be in 1 group, then as suggested by Ronak,
length(unique(cut(x, breaks = seq(0, 1000, by = 50)))) == 1
#[1] TRUE
like image 67
Sotos Avatar answered Jan 08 '23 02:01

Sotos


a data.table solution:

test <- function(u){
  ifelse(all(as.data.table(u)[, 
                              .N, 
                               by = cut(u, 
                                        breaks = seq(0, 1000, 50))][, unique(N)] == 50), 
         TRUE, 
         FALSE)
}

Tests:

x <- 1:50 # TRUE
y <- 2:51 # FALSE
z <- 1:100 # TRUE
w <- 2:101 # FALSE

test(x)
> TRUE

test(y)
> FALSE

test(z)
> TRUE

test(w)
> FALSE
like image 33
PavoDive Avatar answered Jan 08 '23 02:01

PavoDive