我想使用dplyr的select_if函数选择字符和整数类型的变量。但是下面的代码会引发错误。
mpg%>%select_if(is.character | is.integer)我该如何解决……
一种方法是使用匿名函数
library(dplyr) mpg %>% select_if(function(x) is.character(x) | is.integer(x)) # manufacturer model year cyl trans drv cty hwy fl class # <chr> <chr> <int> <int> <chr> <chr> <int> <int> <chr> <chr> # 1 audi a4 1999 4 auto(l5) f 18 29 p compact # 2 audi a4 1999 4 manual(m5) f 21 29 p compact # 3 audi a4 2008 4 manual(m6) f 20 31 p compact # 4 audi a4 2008 4 auto(av) f 21 30 p compact # 5 audi a4 1999 6 auto(l5) f 16 26 p compact # 6 audi a4 1999 6 manual(m5) f 18 26 p compact # 7 audi a4 2008 6 auto(av) f 18 27 p compact # 8 audi a4 quattro 1999 4 manual(m5) 4 18 26 p compact # 9 audi a4 quattro 1999 4 auto(l5) 4 16 25 p compact #10 audi a4 quattro 2008 4 manual(m6) 4 20 28 p compact # �� with 224 more rows
或使用 funs
funs
mpg %>% select_if(funs(is.character(.) | is.integer(.)))
我们可以使用 ~ 同样
~
library(dplyr) mpg %>% select_if(~ is.character(.x)|is.integer(.x))
或者 inherits
inherits
mpg %>% select_if(~ inherits(.x, c("character", "integer")))