Using switch statement within dplyr's mutate

五迷三道 提交于 2021-02-16 20:04:13

问题


I would like to use a switch statement within dplyr's mutate. I have a simple function that performs some operations and assigns alternative values via switch, for example:

convert_am <- function(x) {
    x <- as.character(x)
    switch(x,
           "0" = FALSE,
           "1" = TRUE,
           NA)
}

This works as desired when applied to scalars:

>> convert_am(1)
[1] TRUE
>> convert_am(2)
[1] NA
>> convert_am(0)
[1] FALSE

I would like to arrive at equivalent results via mutate call:

mtcars %>% mutate(am = convert_am(am))

This fails:

Error inmutate_impl(.data, dots) : Evaluation error: EXPR must be a length 1 vector.

I understand that this is because values passed to switch ar not single, as in example:

convert_am(c(1,2,2)) Error in switch(x, 0 = FALSE, 1 = TRUE, NA) : EXPR must be a length 1 vector

Vectorization

Attempt to vectorize also yield the desired results:

convert_am <- function(x) {
    x <- as.character(x)

    fun_switch <- function(x) {
        switch(x,
               "0" = FALSE,
               "1" = TRUE,
               NA)
    }

    vf <- Vectorize(fun_switch, "x")
}

>> mtcars %>% mutate(am = convert_am(am))
Error in mutate_impl(.data, dots) : 
  Column `am` is of unsupported type function

Notes

  • I'm aware of case_when in dplyr and I'm not interested in using it, I'm only interested in making switch work inside mutate
  • Ideal solution would allow for further expansion to use mutate_at with variables passed as .

回答1:


switch is not vectorized so for efficiency you need to use ifelse or case_when - but as your question is specifically about switch, you can achieve what you want by vectorizing, e.g.

convert_am <- Vectorize(function(x) {
    x <- as.character(x)
    switch(x,
       "0" = FALSE,
       "1" = TRUE,
       NA)
})

or

convert_am <- function(x) {
    x <- as.character(x)
    sapply(x, function(xx) switch(xx,
       "0" = FALSE,
       "1" = TRUE,
       NA))
}

They are both inefficient as they involve a loop under the hood.



来源:https://stackoverflow.com/questions/46814076/using-switch-statement-within-dplyrs-mutate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!