[英]How to select non-numeric columns using dplyr::select_if
I need to select all columns that are not numeric. 我需要选择所有非数字的列。 I can select all numeric columns easily using
select_if
: 我可以使用
select_if
轻松选择所有数字列:
mtcars %>% select_if(is.numeric)
What if I want to select non-numeric
columns? 如果我想选择
non-numeric
列怎么办? I tried: 我试过了:
mtcars %>% select_if(!is.numeric)
But I got error message below: 但我收到以下错误消息:
Error in !is.numeric : invalid argument type
Thanks a lot for help! 非常感谢您的帮助!
You can use purrr
's negate()
which is included if you use library(tidyverse)
rather than just library(dplyr)
如果你使用
library(tidyverse)
而不仅仅是library(dplyr)
你可以使用purrr
的negate()
library(dplyr)
library(tidyverse)
iris %>% select_if(negate(is.numeric))
You can use a purrr-style anonymous function, provided you have a reasonably recent version of dplyr: 如果你有一个合理的最新版本的dplyr,你可以使用purrr风格的匿名函数:
library(dplyr)
iris %>% select_if(~!is.numeric(.x)) %>% head()
#> Species
#> 1 setosa
#> 2 setosa
#> 3 setosa
#> 4 setosa
#> 5 setosa
#> 6 setosa
or the old-style funs
notation still works, eg 或者旧式的符号表示法仍然
funs
,例如
iris %>% select_if(funs(!is.numeric(.))) %>% head()
#> Species
#> 1 setosa
#> 2 setosa
#> 3 setosa
#> 4 setosa
#> 5 setosa
#> 6 setosa
One possible solution could be: 一种可能的解决方案是:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.