【问题标题】:How to use dplyr to convert variables from numeric to factor with unique levels如何使用 dplyr 将变量从数字转换为具有唯一级别的因子
【发布时间】:2018-07-27 20:35:51
【问题描述】:

我正在尝试使用因子级别的“码本”(格式化为命名列表的列表)将大量数值变量转换为因子变量。我可以使用mutate()recode_factor() 来一一完成,但我想使用mutate_at() 一次性完成。我该怎么办?

codebook <- list(
  vs = list(`0` = 'V-shaped',
            `1` = 'straight'),
  am = list(`0` = 'automatic',
            `1` = 'manual')
)

mtcars %>%
  mutate(vs = recode_factor(vs, levels = !!!(pluck(codebook, 'vs'))))

mtcars %>%
  mutate_at(vars(names(codebook)),
            funs(recode_factor(., levels = !!!(pluck(codebook, 'somehow_pass_column_name_here?')))))

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    一种选择是循环遍历“codebook”的names

    library(tidyverse)
    names(codebook) %>%
       map(~ mtcars %>% 
               transmute(!! .x := recode_factor(!! rlang::sym(.x), 
                            levels  = !!!(pluck(codebook, .x))))) %>% 
       bind_cols(mtcars %>%
       select(-one_of(names(codebook))), .)
    

    或使用for 循环

    library(magrittr)
    for(nm in names(codebook)) {
      mtcars %<>%
            mutate(!! nm := recode_factor(!! rlang::sym(nm), 
                   levels = !!!(pluck(codebook, nm))))
    }
    

    【讨论】:

      【解决方案2】:

      您仍然可以将mutate 用于多个变量,除非您的意思是一对一。我不太熟悉mutate_at,所以也许有人知道这种方法。

      mtcars %>%
        mutate(vs = recode_factor(vs, levels = !!!(pluck(codebook, 'vs'))),
               am = recode_factor(am, levels = !!!(pluck(codebook, 'am'))))
      
          mpg cyl  disp  hp drat    wt  qsec       vs        am gear carb
      1  21.0   6 160.0 110 3.90 2.620 16.46 V-shaped    manual    4    4
      2  21.0   6 160.0 110 3.90 2.875 17.02 V-shaped    manual    4    4
      3  22.8   4 108.0  93 3.85 2.320 18.61 straight    manual    4    1
      4  21.4   6 258.0 110 3.08 3.215 19.44 straight automatic    3    1
      5  18.7   8 360.0 175 3.15 3.440 17.02 V-shaped automatic    3    2
      6  18.1   6 225.0 105 2.76 3.460 20.22 straight automatic    3    1
      7  14.3   8 360.0 245 3.21 3.570 15.84 V-shaped automatic    3    4
      8  24.4   4 146.7  62 3.69 3.190 20.00 straight automatic    4    2
      9  22.8   4 140.8  95 3.92 3.150 22.90 straight automatic    4    2
      10 19.2   6 167.6 123 3.92 3.440 18.30 straight automatic    4    4
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-25
        • 2019-02-21
        • 2017-05-14
        • 2021-11-22
        • 1970-01-01
        相关资源
        最近更新 更多