2

我正在清理数据集,需要重新编码许多因子变量。我想使用rlangmap创建一个函数来做到这一点。我的示例数据集和代码如下。我想我几乎明白了,但我似乎无法弄清楚这个错误,可能是因为我没有完全掌握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)​​.

4

1 回答 1

0

使用@epi10 提出的建议,这可行,但不使用rlangor map

df1 <- df1 %>%
  mutate_at(vars(var1, var2, var3),
        function(x) case_when(x <= 1 ~ 0,
                              x <= 2 ~ 1,
                              x <= 3 ~ 2))
于 2018-02-06T14:13:41.250 回答