paljenczy
paljenczy

Reputation: 4899

dplyr - how to select columns of certain type

Is there a concise way to select columns of certain type in dplyr? For example, how to select all character columns within a dplyr chain?

Upvotes: 30

Views: 20949

Answers (4)

Levi Baguley
Levi Baguley

Reputation: 738

As of dplyr 1.0.0 *_if functions and friends have been superseded. Using the selection helper where from tidyselect is now recommended.

https://dplyr.tidyverse.org/reference/select.html
https://tidyselect.r-lib.org/reference/where.html

library(dplyr)

starwars %>% 
    select(where(is.character))
#> # A tibble: 87 x 8
#>    name        hair_color   skin_color eye_color sex   gender  homeworld species
#>    <chr>       <chr>        <chr>      <chr>     <chr> <chr>   <chr>     <chr>  
#>  1 Luke Skywa~ blond        fair       blue      male  mascul~ Tatooine  Human  
#>  2 C-3PO       <NA>         gold       yellow    none  mascul~ Tatooine  Droid  
#>  3 R2-D2       <NA>         white, bl~ red       none  mascul~ Naboo     Droid  
#>  4 Darth Vader none         white      yellow    male  mascul~ Tatooine  Human  
#>  5 Leia Organa brown        light      brown     fema~ femini~ Alderaan  Human  
#>  6 Owen Lars   brown, grey  light      blue      male  mascul~ Tatooine  Human  
#>  7 Beru White~ brown        light      blue      fema~ femini~ Tatooine  Human  
#>  8 R5-D4       <NA>         white, red red       none  mascul~ Tatooine  Droid  
#>  9 Biggs Dark~ black        light      brown     male  mascul~ Tatooine  Human  
#> 10 Obi-Wan Ke~ auburn, whi~ fair       blue-gray male  mascul~ Stewjon   Human  
#> # ... with 77 more rows

Created on 2020-06-02 by the reprex package (v0.3.0)

Upvotes: 21

Rickard
Rickard

Reputation: 3690

Dplyr 0.5 has the select_if() that allows you to write select_if(is.character)

Upvotes: 51

Koundy
Koundy

Reputation: 5555

You can do this with

dt %>% select(which(sapply(.,is.character)))

Upvotes: 14

Tal J. Levy
Tal J. Levy

Reputation: 598

One way to go about it would be first to obtain the classes of the different columns. So assuming we have some data:

library(dplyr)
DT <- data.frame(A = letters[1:6], B = c(T,F,F), C = seq(1,2,length.out = 6), D = 1:6)
dt <- tbl_df(DT)
dt$A <- as.character(dt$A)
output
       A     B     C     D
  (chr) (lgl) (dbl) (int)
1      a  TRUE   1.0     1
2      b FALSE   1.2     2
3      c FALSE   1.4     3
4      d  TRUE   1.6     4
5      e FALSE   1.8     5
6      f FALSE   2.0     6

We can now obtain the classes using the which function:

cls <- sapply(dt, class)
cls
output
        A         B         C         D 
 "character" "logical" "numeric" "integer" 

Now it is straight forward:

newDF <- dt %>% select(which(cls=="character"))
newDF
output
      A
  (chr)
1     a
2     b
3     c
4     d
5     e
6     f

Upvotes: 5

Related Questions