【问题标题】:set factor levels in specific order [duplicate]按特定顺序设置因子水平[重复]
【发布时间】:2021-11-07 16:45:46
【问题描述】:

如何按特定顺序设置级别? 所需的级别顺序是 - "CA", "IN", "FL" "NY"

library(dplyr)

tbl <- tibble(states = c("FL", "NY", "CA", "IN")) %>%
  mutate(states_fct = factor(states))

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    使用levels = 参数。

    tbl <- tibble(states = c("FL", "NY", "CA", "IN")) %>%
      mutate(states_fct = factor(states, levels = c("CA", "IN", "FL", "NY"))
    

    【讨论】:

      【解决方案2】:

      您可以使用ordered 表示您想要一个有序因子:

      states = ordered(c("FL", "NY", "CA", "IN"), levels = c("CA", "IN", "FL", "NY"))
      str(states)
      

      【讨论】:

        【解决方案3】:

        我们可以使用来自forcats 包的fct_relevel:

        library(dplyr)
        library(forcats)
        tbl <- tibble(states = c("FL", "NY", "CA", "IN")) %>%
            mutate(states_fct = factor(states)) %>% 
            mutate(states_fct = fct_relevel(states_fct, c("CA", "IN", "FL", "NY")))
        
        levels(tbl$states_fct)
        
        

        输出:

          states states_fct
          <chr>  <fct>     
        1 FL     FL        
        2 NY     NY        
        3 CA     CA        
        4 IN     IN        
        
        > levels(tbl$states_fct)
        [1] "CA" "IN" "FL" "NY"
        

        【讨论】:

          猜你喜欢
          • 2018-12-07
          • 1970-01-01
          • 1970-01-01
          • 2017-07-12
          • 2017-07-14
          • 1970-01-01
          • 1970-01-01
          • 2014-09-29
          • 2012-07-20
          相关资源
          最近更新 更多