Check if the value is within the range?

I have a dataset in data.table format that looks like this:

 ID time.s time.e 1 1 2 2 1 4 3 2 3 4 2 4 

I want to check if value 1 is between time.s and time.e so that the final result looks like

 [1] TRUE TRUE FALSE FALSE 

How can i do this? I tried to use

  a[1 %in% seq(time.s, time.e)] 

But all that I get is all TRUE values. Any recommendations?

+8
source share
5 answers

Assuming ID values ​​are unique:

 DT[, list(OK = 1 %in% seq(time.s, time.e)), by = ID] 

gives

  ID OK 1: 1 TRUE 2: 2 TRUE 3: 3 FALSE 4: 4 FALSE 
+7
source

In addition, this works:

 with(dat, time.s <= 1 & time.e >= 1) 
+6
source

Here's a dplyr option in case anyone dplyr this question:

 library(dplyr) value = 1 df %>% mutate(ok = value >= time.s & value <= time.e) ID time.s time.e ok 1 1 1 2 TRUE 2 2 1 4 TRUE 3 3 2 3 FALSE 4 4 2 4 FALSE 
+3
source

Here is another one.

 library(TeachingDemos) a[time.s %<=% 1 %<=% time.e] 

It is probably too difficult to load the library for this, but the syntax is pretty intuitive.

+1
source

Just adding to the tools that can be used for this, the other is data.table::between :

 data.frame <- data.frame(ID = 1:4, time.s = c(1,1,2,2), time.e = c(2,4,3,4)) data.table::between(1, data.frame$time.s, data.frame$time.e) 
0
source

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


All Articles