Search code examples
rdplyrcrannse

combining mutate_at with case_when


I have to transform the following code:

labels = 'x'
dataX <- data.frame(x = colors())
special <- sample(colors(),5)
dataX <- dataX %>% mutate("names2" := dplyr::case_when(UQ(sym(labels)) %in% special ~ UQ(sym(labels))))

Into some code which will work without := since this gives me a NOTE when running a package check.

Therefore I am trying to use mutate_at instead but can't combine it with case_when:

dataX <- dataX %>% mutate_at(c("names3" = labels) , funs(dplyr::case_when(.) %in% special ~ .))

which fails with:

Error in mutate_impl(.data, dots) : 
  Column `names3` is of unsupported type quoted call

Therefore, my question.

So far the best I came up with is:

testx <- function(x, special){tmp <- x %in% special; x[!tmp] <- NA; as.character(x)}
dataX <- dataX %>% mutate_at(c("names4" = labels) , funs(testx(., special)))

Solution

  • This looks like a syntax error to me. Just put the brackets in the right place:

    dataX %>%
      mutate_at(c("names3" = labels),
                funs(dplyr::case_when(. %in% special ~ .))) %>% 
      filter(!is.na(names3)) 
    #>            x     names2     names3
    #> 1     grey41     grey41     grey41
    #> 2     grey72     grey72     grey72
    #> 3     grey89     grey89     grey89
    #> 4 mistyrose4 mistyrose4 mistyrose4
    #> 5 steelblue2 steelblue2 steelblue2