【问题标题】:How to select non-numeric columns using dplyr::select_if如何使用 dplyr::select_if 选择非数字列
【发布时间】:2018-07-03 23:51:46
【问题描述】:

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

mtcars %>% select_if(is.numeric)

如果我想选择non-numeric 列怎么办?我试过了:

mtcars %>% select_if(!is.numeric)

但我收到以下错误消息:

Error in !is.numeric : invalid argument type

非常感谢您的帮助!

【问题讨论】:

标签: r dplyr


【解决方案1】:

您可以使用 purrr 风格的匿名函数,前提是您拥有相当新的 dplyr 版本:

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(.))
  • 是的,我在 purrr 风格的函数中使用 .x,因为它更容易区分使用 . 告诉管道放置数据的位置。
  • 哦,我明白了,我认为您必须对管道对象使用 dplyr 语法。不知道 purr 风格的管道标识符,非常感谢
【解决方案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

【讨论】:

    【解决方案3】:

    您可以使用purrrnegate(),如果您使用library(tidyverse) 而不仅仅是library(dplyr),则包含该library(dplyr)

    library(tidyverse)
    iris %>% select_if(negate(is.numeric))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-31
      相关资源
      最近更新 更多