3

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
Grec001
  • 1,111
  • 6
  • 20

1 Answers1

3

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"))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks, @akrun I think you r saying `Filter(function(x) class(x) %in% c("integer", "numeric"), DF)'. it does work, now I will go further on `POSIXct` and see it works. Thanks, sir, U r truly a respectful mentor. – Grec001 May 17 '18 at 05:55
  • 1
    @Grec001 Do you want to remove those columns or keep it? – akrun May 17 '18 at 05:59
  • I wanna find them, and work on them. So you gave a perfect answer if I remove the `!`. The Filter way is smart. – Grec001 May 17 '18 at 06:01
  • 1
    @Grec001 In that case, just remove the `!` in the pipe in the `Filter` – akrun May 17 '18 at 06:02
  • you should use inherits, not class – MichaelChirico May 17 '18 at 06:11
  • @MichaelChirico I tried `inherits(DF, c("integer", "numeric", "POSIXct"), TRUE)`, and it gave no result. Would you mind sharing? That would be great! – Grec001 May 17 '18 at 06:21
  • 2
    @Grec001 don't use `exact = TRUE` -- compare `inherits(1L, c('numeric', 'integer', 'POSIXct'), TRUE)` and `inherits(1L, c('numeric', 'integer', 'POSIXct'))` – MichaelChirico May 17 '18 at 06:43