16

I have a dataset in a data.table format that looks as such:

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

I want to check to see if the value 1 is within time.s and time.e so that the end result would look like

[1] TRUE TRUE FALSE FALSE

How would I go about this? I have tried to use

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

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

Jaap
  • 81,064
  • 34
  • 182
  • 193
akash87
  • 3,876
  • 3
  • 14
  • 30

7 Answers7

15

Also, this works:

with(dat, time.s <= 1 & time.e >= 1)
akash87
  • 3,876
  • 3
  • 14
  • 30
8

Assuming that the values of ID are unique:

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

giving;

   ID    OK
1:  1  TRUE
2:  2  TRUE
3:  3 FALSE
4:  4 FALSE
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • 2
    This unfortunately only works with discrete (unitary? I'm missing the word here but I hope the meaning comes through) values of time... e.g. 2 is in seq(1, 3) but 2.2 is not. And of course one can specify the step of seq() but that only solves this much.. – Stefano Mar 21 '19 at 10:09
8

Here's a dplyr option in case anybody stumbles on 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
sbha
  • 9,802
  • 2
  • 74
  • 62
  • 1
    Thank you for the dplyr answer, it's so simple but I was stuck in a base-R mindset while trying to do this on a project. – Andrew Brēza Jan 28 '19 at 15:38
5

Just adding to the tools that could be used to this, another being 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)
Lalochezia
  • 497
  • 4
  • 15
1

Here's another one.

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

It's probably overkill to load a library for that, but the syntax is quite intuitive.

RHertel
  • 23,412
  • 5
  • 38
  • 64
0

Here is another answer with base r:

data.frame <- data.frame(ID = 1:4,
                         time.s = c(1,1,2,2),
                         time.e = c(2,4,3,4))

data.frame$OK<-data.frame$ID%in%c(data.frame$time.s:data.frame$time.e)

data.frame
  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
0

you can also use the function dplyr::between(x,left, right) see here

AleRuete
  • 313
  • 3
  • 7