dplyr - 如何选择某种类型的列

时间:2015-12-30 08:20:15

标签: r dplyr

是否有简明的方法在dplyr中选择特定类型的列?例如,如何选择dplyr链中的所有字符列?

4 个答案:

答案 0 :(得分:32)

Dplyr 0.5的select_if()允许您编写select_if(is.character)

答案 1 :(得分:12)

您可以使用

执行此操作
dt %>% select(which(sapply(.,is.character)))

答案 2 :(得分:5)

一种方法是首先获取不同列的类。假设我们有一些数据:

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)
产量
       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

我们现在可以使用 函数获取类:

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

现在很直接:

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

答案 3 :(得分:4)

dplyr 1.0.0起*_if的功能和朋友已被取代。现在建议使用where中的selection helper tidyselect

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

reprex package(v0.3.0)于2020-06-02创建