在dplyr
中有没有一种简洁的方法来选择某个类型的列?例如,在dplyr
链中如何选择所有字符列?
Dplyr 0.5 版本添加了 select_if()
方法,可以使用 select_if(is.character)
来筛选字符类型的列。
dplyr
1.0.0 版本,*_if
函数及其相关函数已被取代。现在建议使用选择助手where
,该助手来自于tidyselect
。
https://dplyr.tidyverse.org/reference/select.htmllibrary(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日创建的
您可以使用以下方法来完成这个任务
dt %>% select(which(sapply(.,is.character)))
一种处理方法是首先获取不同列的类。假设我们有一些数据:
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
class
函数的东西吗?类似于这样:d <- tbl_df(iris); type_sum(d); select(d,which(type_sum(d)=="dbl"))
- Roman