按组获取变量类型列表

时间:2018-06-14 03:44:04

标签: r

我知道如何获取变量类型列表:

mtcars$vs <- factor(mtcars$vs)
mtcars$am <- factor(mtcars$am)
mtcars$gear <- factor(mtcars$gear)
mtcars$carb <- factor(mtcars$carb)

unlist(lapply(mtcars, class))
  mpg       cyl      disp        hp      drat        wt      qsec        vs        am      gear      carb 
"numeric" "numeric" "numeric" "numeric" "numeric" "numeric" "numeric"  "factor"  "factor"  "factor"  "factor" 

但有没有办法要么只返回一个类的变量(例如因子),要么按类分组完整列表?我希望能够快速识别所有数字,因子等变量。例如:

void*

1 个答案:

答案 0 :(得分:1)

您可以使用dplyr::select_if()根据结构选择列。

require(tidyverse)

diamonds %>% 
  select_if(is.factor)

# A tibble: 53,940 x 3
   cut       color clarity
   <ord>     <ord> <ord>  
 1 Ideal     E     SI2    
 2 Premium   E     SI1    
 3 Good      E     VS1    
 4 Premium   I     VS2    
 5 Good      J     SI2    
 6 Very Good J     VVS2   
 7 Very Good I     VVS1   
 8 Very Good H     SI1    
 9 Fair      E     VS2    
10 Very Good H     VS1    
# ... with 53,930 more rows