是否有简明的方法在dplyr
中选择特定类型的列?例如,如何选择dplyr
链中的所有字符列?
答案 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创建