dplyr - 如何选择特定类型的列

30

dplyr中有没有一种简洁的方法来选择某个类型的列?例如,在dplyr链中如何选择所有字符列?


不太熟悉dplyr包。但是你能做类似于class函数的东西吗?类似于这样:d <- tbl_df(iris); type_sum(d); select(d,which(type_sum(d)=="dbl")) - Roman
4个回答

51

Dplyr 0.5 版本添加了 select_if() 方法,可以使用 select_if(is.character) 来筛选字符类型的列。


3
使用这种方法比在dplyr链内部使用apply函数会让代码更加简洁! - Stefan Avey

19
截至 dplyr 1.0.0 版本,*_if 函数及其相关函数已被取代。现在建议使用选择助手where,该助手来自于tidyselecthttps://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日创建的


14

您可以使用以下方法来完成这个任务

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

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

我们现在可以使用which函数获取类:
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

不错 - 我正在寻找可能避免在dplyr链外获取类的方法。 - paljenczy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接