使用rlang和map重新编码R中的许多变量

时间:2017-12-21 16:10:16

标签: r tidyverse purrr rlang

我正在清理数据集,需要重新编码许多因子变量。我想使用rlangmap创建一个函数来执行此操作。我的示例数据集和代码如下。我想我几乎得到了它,但我似乎无法弄清楚这个bug,可能是因为我没有完全掌握rlang

工作数据集:

df1 <- tribble(
~var1, ~var2, ~var3,
"1",   "1",   "1",
"2",   "2",   "2",
"3",   "3",   "3"
)

以下是我将如何重新编码单个变量(以及我想要的结果):

df1 <- df1 %>%
  mutate(var1 = fct_recode(var1,
                          "0" = "1",
                          "1" = "2",
                          "2" = "3")) 

这是我的工作代码:

recode = function(...){
  mutate_quo = quos(...)

  map(mutate_quo, ~{
    df1 <- df1 %>%
      mutate(!!.x = fct_recode(!!.x,
                         "0" = "1",
                         "1" = "2",
                         "2" = "3"))
  })
}

这会出现以下错误:

Error: unexpected '=' in:
"    df1 <- df1 %>%
  mutate(!!.x ="
>                              "0" = "1",
Error: unexpected ',' in "                             "0" = "1","
>                              "1" = "2",
Error: unexpected ',' in "                             "1" = "2","
>                              "2" = "3"))
Error: unexpected ')' in "                             "2" = "3")"
>   })
Error: unexpected '}' in "  }"
> }
Error: unexpected '}' in "}"

如果删除!!,函数将编译。但是,当我尝试使用recode("var1")调用它时,我收到以下错误:

Error in mutate_impl(.data, dots) : 
Evaluation error: `f` must be a factor (or character vector).. 

我想拥有该功能,然后运行recode(var1, var2, var3)

1 个答案:

答案 0 :(得分:0)

使用@ epi10提供的建议,这有效但不使用rlangmap

df1 <- df1 %>%
  mutate_at(vars(var1, var2, var3),
        function(x) case_when(x <= 1 ~ 0,
                              x <= 2 ~ 1,
                              x <= 3 ~ 2))