我需要选择所有非数字列。我可以使用 select_if
轻松选择所有数字列:
我需要选择所有非数字列。我可以使用
select_if
轻松选择所有数字列:mtcars %>% select_if(is.numeric)
如果我想选择非数字
列,该怎么办?我尝试了:
mtcars %>% select_if(!is.numeric)
但是我收到了以下错误信息:
Error in !is.numeric : invalid argument type
非常感谢您的帮助!
我需要选择所有非数字列。我可以使用 select_if
轻松选择所有数字列:
select_if
轻松选择所有数字列:mtcars %>% select_if(is.numeric)
如果我想选择非数字
列,该怎么办?我尝试了:
mtcars %>% select_if(!is.numeric)
但是我收到了以下错误信息:
Error in !is.numeric : invalid argument type
非常感谢您的帮助!
purrr
的 negate()
函数,如果你使用的是 library(tidyverse)
而不是仅仅使用 library(dplyr)
。library(tidyverse)
iris %>% select_if(negate(is.numeric))
如果您有一个相对较新的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
.
)代替(.x)
,就像这样 iris %>% select_if(〜!is.numeric(.))
。 - Agile Bean.x
,因为这样更容易区分使用 .
来告诉管道放置数据的位置。 - alistairedf[, !(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