简体   繁体   English

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

[英]Using rlang and map to recode many variables in R

I am cleaning a data set and need to recode many factor variables. 我正在清理数据集,需要重新编码许多因子变量。 I would like to use rlang and map to create a function to do this. 我想使用rlangmap创建一个函数来做到这一点。 My example dataset and code are below. 我的示例数据集和代码如下。 I think I almost got it, but I just can't seem to figure out the bug, probably because I don't fully grasp rlang . 我想我几乎明白了,但我似乎无法弄清楚该错误,可能是因为我没有完全掌握rlang

Working dataset: 工作数据集:

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

Here is how I would recode a single variable (and the result I would like): 这是我重新编码单个变量的方式(以及我想要的结果):

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

Here is my working code: 这是我的工作代码:

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

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

This gives the following error: 这给出了以下错误:

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 "}"

If I remove the !! 如果我删除了!! , the function will compile. ,函数将编译。 However, when I then try to call it using recode("var1") , I get the following error: 但是,当我尝试使用recode("var1")调用它时,出现以下错误:

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

I would like to have the function and then just run recode(var1, var2, var3) . 我想拥有该功能,然后只运行recode(var1, var2, var3)

Using the suggesting made by @epi10, this works but doesn't use rlang or map . 使用@ epi10的建议,此方法有效,但不使用rlangmap

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM