【问题标题】:Get the names of all factors with more than one level获取多于一级的所有因子的名称
【发布时间】:2022-08-16 23:52:49
【问题描述】:

我有如下示例数据:

mtcars <- mtcars
# Creates a factor with one level
mtcars$vs <- 1
mtcars$vs <- as.factor(mtcars$vs)
# Creates a factor with 2 levels
mtcars$am <- as.factor(mtcars$am)

我想简单地获取具有多个级别的所有因素的名称,所以:

names_of_factors_with_more_lvls <- \"am\"

实现这一目标的最短方法是什么?

    标签: r r-factor


    【解决方案1】:

    我们可以使用nlevels 创建一个逻辑条件——使用select 选择属于factor 类的列,并将其与下一个条件短路(&amp;&amp;),然后检索列名

    library(dplyr)
    mtcars %>%
       select(where(~ is.factor(.x) && nlevels(.x) > 1)) %>%
       names
    [1] "am"
    

    【讨论】:

      【解决方案2】:

      在基础 R 中:

      fa <- mtcars[, sapply(mtcars, is.factor)] 
      names(fa[, sapply(fa, function(x) length(levels(x))) > 1, drop = F])
      #[1] "am"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-25
        • 1970-01-01
        相关资源
        最近更新 更多