简体   繁体   English

使用多个条件的 r 数据帧中的分隔因子和字符列

[英]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.

相关问题 使用 r 计算 data.frame 多列中的字符出现次数 - using r to count character occurrences in multiple columns of data.frame 使用apply()函数更新R中数据帧的多列的因子级别 - Using apply() function to update the factor levels of multiple columns of a data frame in R 在 R 中的数据帧上使用 approx 保留类型因子的列 - keep columns of type factor using approx on a data frame in R 通过分隔现有列中的字符串向数据框中添加新列 - Add new columns to a data frame by separating character strings in an existing column 如何使用R基于匹配查找数据框替换数据框多列中的因子水平 - How to replace factor levels in multiples columns of a data frame based on the match lookup data frame using R 在R中的特定数据框列中替换多个字符串 - Replacing multiple character strings in specific data frame columns in R R:替换数据帧的多列中的特殊字符 - R: replacing special character in multiple columns of a data frame 如何将多个字符列合并为 R 数据框中的单个列 - How to combine multiple character columns into a single column in an R data frame R:使用多列数据创建因子 - R: creating factor using data from multiple columns 用因子对象替换数据框的列而不是插入字符数据? - Replacing columns of data frame with factor object instead inserts character data?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM