Search code examples
rdplyrtidyversetidyselect

Using start_with function along with collapse::fselect funcation


The starts_with("O") from tidyselect works well with dplyr::select function but not with collapse::fselect. Wondering if I'm missing some basic here.

library(collapse)
library(tidyverse)
wlddev %>% 
  select(starts_with("O")) %>% 
  head()
#>    OECD       ODA
#> 1 FALSE 116769997
#> 2 FALSE 232080002
#> 3 FALSE 112839996
#> 4 FALSE 237720001
#> 5 FALSE 295920013
#> 6 FALSE 341839996

wlddev %>% 
  fselect(starts_with("O")) %>% 
  head()
#> Error:
#> ! `starts_with()` must be used within a *selecting* function.
#> i See <https://tidyselect.r-lib.org/reference/faq-selection-context.html>.

Solution

  • We may use gvr

    library(collapse)
    wlddev %>% 
      gvr("^O") %>%
      head
       OECD       ODA
    1 FALSE 116769997
    2 FALSE 232080002
    3 FALSE 112839996
    4 FALSE 237720001
    5 FALSE 295920013
    6 FALSE 341839996
    

    fsum can group in g

    fsum(gvr(wlddev, "^O"), g = wlddev[["iso3c"]])
        OECD          ODA
    ABW    0    664899998
    AFG    0  89252909923
    AGO    0  15512219971
    ALB    0  10013700017
    AND    0           NA
    ARE    0    602289998
    ARG    0   6415849996
    ARM    0   8190379934
    ASM    0           NA
    ATG    0    420559999
    AUS   61           NA
    AUT   61           NA
    AZE    0   5049070016
    BDI    0  17767379852
    BEL   61           NA
    BEN    0  18904160029
    ...
    

    Or with pipe

    wlddev %>% 
      gvr("^O") %>%
      fsum(., g = slt(wlddev, iso3c))
    

    -output

      OECD          ODA
    ABW    0    664899998
    AFG    0  89252909923
    AGO    0  15512219971
    ALB    0  10013700017
    AND    0           NA
    ARE    0    602289998
    ...
    

    Or may use

    wlddev %>% 
      fgroup_by(iso3c) %>% 
      gvr("^O") %>% 
      fsum
    

    -output

       iso3c OECD          ODA
    1     ABW    0    664899998
    2     AFG    0  89252909923
    3     AGO    0  15512219971
    4     ALB    0  10013700017
    5     AND    0           NA
    6     ARE    0    602289998
    7     ARG    0   6415849996
    8     ARM    0   8190379934
    9     ASM    0           NA
    10    ATG    0    420559999
    ...