如何使用dplyr::select_if选择非数值列。

28

我需要选择所有非数字列。我可以使用 select_if 轻松选择所有数字列:


我需要选择所有非数字列。我可以使用 select_if 轻松选择所有数字列:
mtcars %>% select_if(is.numeric)

如果我想选择非数字列,该怎么办?我尝试了:

mtcars %>% select_if(!is.numeric)

但是我收到了以下错误信息:

Error in !is.numeric : invalid argument type

非常感谢您的帮助!


1
请看这里:https://dev59.com/DVkS5IYBdhLWcg3wp4Mh - Sean Lin
3个回答

43
你可以使用 purrrnegate() 函数,如果你使用的是 library(tidyverse) 而不是仅仅使用 library(dplyr)
library(tidyverse)
iris %>% select_if(negate(is.numeric))

10

如果您有一个相对较新的dplyr版本,您可以使用purrr风格的匿名函数:

library(dplyr)

iris %>% select_if(~!is.numeric(.x)) %>% head()
#>   Species
#> 1  setosa
#> 2  setosa
#> 3  setosa
#> 4  setosa
#> 5  setosa
#> 6  setosa

或者仍然可以使用旧式的funs符号表示,例如:

iris %>% select_if(funs(!is.numeric(.))) %>% head()
#>   Species
#> 1  setosa
#> 2  setosa
#> 3  setosa
#> 4  setosa
#> 5  setosa
#> 6  setosa

太棒了 - 即使@MrFlick的解决方案可行,但我更喜欢这个解决方案,因为你不需要加载另一个库。仅有一点要注意:上面的代码也可以使用点(.)代替(.x),就像这样 iris %>% select_if(〜!is.numeric(.)) - Agile Bean
是的,我在 purrr 风格的函数中使用 .x,因为这样更容易区分使用 . 来告诉管道放置数据的位置。 - alistaire
哦,我明白了,我以为你必须使用dplyr语法来处理管道对象。不知道还有purrr风格的管道标识符,非常感谢。 - Agile Bean

2
一种可能的解决方案是:
df[, !(names(df) %in% names(df %>% select_if(is.numeric)))]

Example:
df <- data.frame(
  name = c( "a", "b", "c", "d" ),
  last_name = c( "r", "t", "s", "b" ),
  x = c( 3, 2, 1, 2 ),
  y = c( 4, 3, 4, 3 ),
  z = c( 8, 9, 6, 7 ) , stringsAsFactors = FALSE)
> df[, !(names(df) %in% names(df %>% select_if(is.numeric)))]
#  name last_name
#1    a         r
#2    b         t
#3    c         s
#4    d         b

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