1

I am trying to apply a custom function using switch inside a mutate command, but I keep on getting the following error.

Error: Problem with `mutate()` input `new_col`.
x EXPR must be a length 1 vector
ℹ Input `new_col` is `example_func(col_name, trans)`.

My desired end result is a string that will later be executed as a function.

library(tidyverse)

## sample function
example_func <- function(pred, trans) {
  switch(trans,
         "None" = pred,
         "Squared" = paste0(pred, "^2")
  )
}

## test function (works)
example_func("b", "")

## data
dat <- data.frame(col_name = c("a", "b"),
                  trans = c("Squared", "None"))

## desired end result
dat[["new_col"]] <- c("a^2", "b")
dat

## trying to apply function to data (fails)
dat %>% 
  mutate(new_col = example_func(col_name, trans))
DJC
  • 1,491
  • 6
  • 19
  • 1
    `switch()` is not a vectorized function. If you are going to use dplyr function, better to use `case_when`: `example_func <- function(pred, trans) {case_when(trans=="None" ~ pred, trans=="Squared" ~ paste0(pred, "^2"))}` – MrFlick Oct 26 '20 at 22:27

1 Answers1

0

We can use rowwise because the function is switch and switch takes a vector of length 1 for 'EXPR'

According to ?switch

EXPR - an expression evaluating to a number or a character string.

So, it is not numbers or strings

library(dplyr)
dat %>% 
   rowwise %>% 
   mutate(new_col = example_func(col_name, trans)) %>%
   ungroup
akrun
  • 874,273
  • 37
  • 540
  • 662