How does dplyr’s between work?

前端 未结 3 1848
说谎
说谎 2020-12-14 09:09

I’ve read the documentation and I’ve tried googling it; it should be a simple thing, but it would seem it’s not to me; so I boldly go forth and ask if someone here could exp

相关标签:
3条回答
  • 2020-12-14 09:44

    I guess you want it like this:

    library(nycflights13)
    library(dplyr)
    
    flights %>% filter(between(month,7,9))
    

    I see in the meantime this solution also appeared in the comments.

    0 讨论(0)
  • 2020-12-14 09:45

    between is nothing special — any other function in R would have led to the same problem. Your confusion stems from the fact that dplyr has a lot of functions that allow you to work on data.frame column names as if they were normal variables; for instance:

    filter(flights, month > 9)
    

    However, between is not one of these functions. As mentioned, it’s simply a normal function. So if you want to use it, you need to provide arguments in the conventional way; for instance:

    between(flights$month, 7, 9)
    

    This will return a logical vector, and you can now use it to index your data.frame:

    flights[between(flights$month, 7, 9), ]
    

    Or, more dplyr-like:

    flights %>% filter(between(month, 7, 9))
    

    Note that here we now use non-standard evaluation. But the evaluation is performed by filter, not by between. between is called (by filter) using standard evaluation.

    0 讨论(0)
  • 2020-12-14 10:07

    filter(flights, between(month, 7,9)) seems to work just fine

    0 讨论(0)
提交回复
热议问题