[英]separating factor and character columns in r data frame using multiple condition
I would like to separate only two types of a column of the data frame (factors and characters) and the following codes results in an error.我只想分隔数据框的两种类型的列(因子和字符),以下代码会导致错误。 I wonder what is the correct way to carry out this task.
我想知道执行此任务的正确方法是什么。
install.packages("dslabs")
library(dslabs)
data(murders)
names(murders)[sapply(murders, (is.factor | is.character))]
I can use the following code to combine the two, but I wonder what will be the correct format in case I want to use multiple conditions as the code above.我可以使用下面的代码将两者结合起来,但我想知道如果我想使用多个条件作为上面的代码,正确的格式是什么。
c(names(murders)[sapply(murders, is.factor)],names(murders)[sapply(murders, is.character)])
We may need a lambda function我们可能需要 lambda function
names(murders)[sapply(murders, function(x)
is.factor(x) | is.character(x))]
Or another option is to get the class
and use %in%
或者另一种选择是获取
class
并使用%in%
names(murders)[sapply(murders, class) %in% c("factor", "character")]
Or with Filter
或带
Filter
names(Filter(function(x) is.factor(x)|is.character(x), murders))
Or using tidyverse
或使用
tidyverse
library(dplyr)
murders %>%
select(where(~ is.factor(.x)|is.character(.x))) %>%
names
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.