Check to see if a value is within a range?

前端 未结 5 1275
孤独总比滥情好
孤独总比滥情好 2020-12-10 13:17

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         


        
相关标签:
5条回答
  • 2020-12-10 13:35

    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)
    
    0 讨论(0)
  • 2020-12-10 13:41

    Also, this works:

    with(dat, time.s <= 1 & time.e >= 1)
    
    0 讨论(0)
  • 2020-12-10 13:46

    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
    
    0 讨论(0)
  • 2020-12-10 13:47

    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.

    0 讨论(0)
  • 2020-12-10 13:55

    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
    
    0 讨论(0)
提交回复
热议问题