Search code examples
rmagrittr

How shall I properly address the pipe?


Trying to make magrittr pinping function more graceful and readable. However, the best I can do about this is as following. How can I improve it? Please find the referential code, and advise. Thanks

DF <- data.frame(a=letters[1:10], b=1L:10L, c=1.01:1.10, d=rep(TRUE,10), e=10L:1L)

cols <- lapply(DF,class) %>% unlist()
cols[which(cols %in% c("integer","numeric"))]

#        b         c         e 
#"integer" "numeric" "integer"
#
# yet, I'd still like to get rid of the variables.  

the best I can do in piping is like this. Tried with %$%, but failed.

(lapply(DF,class) %>% unlist)[
which(lapply(DF,class) %>% unlist() =="integer" |
      lapply(DF,class) %>% unlist() =="numeric")]

can I make it something like this?

lapply(DF,class) %>% unlist %$% .[which(. %in% c("integer","numeric"))]
# of course, it doesn't work

Solution

  • We could use Filter from base R to remove those columns with class integer or numeric

    Filter(function(x) !class(x) %in% c("integer", "numeric"), DF)
    

    For keeping those variables

    Filter(function(x) class(x) %in% c("integer", "numeric"), DF)
    

    Or using the %>%, get the class of the columns with map, check whether it is %in%, 'integer' or 'numeric', negate (! - only if we need to remove those variables) and magrittr::extract the columns based on the logical index

    library(tidyverse)
    map_chr(DF, class) %>% 
        `%in%`(c("integer", "numeric")) %>% 
        #`!` %>%  #in case to remove those columns
        extract(DF, .)
    

    Or with discard to remove the columns

    discard(DF, ~class(.x) %in% c("integer", "numeric"))
    

    or keep to keep the columns

    keep(DF, ~ class(.x) %in% c("integer", "numeric"))