Help with a function

Hello. I am a relative newcomer to R and I'm having some difficulty with what I thought would be a fairly simple function. Here is a sample:

Recode01 <- function(data, varname) {
  varname = enquo(varname)
  data <- data %>%
    mutate((!!varname) :=
        case_when((!!varname) == 1 ~ 4,
                  (!!varname) == 2 ~ 3,
                  (!!varname) == 3 ~ 1,
                  (!!varname) == 4 ~ 0,
                  (!!varname) == 5 ~ 2))
  
}

col1 <- c(1:5)
df1 <- as.data.frame(col1)
Recode01(df1, col1)

When I submit this literally nothing happens. Please note that when submitted as straight code it works as intended. See:

df1 <- df1 %>% 
    mutate(col1 =
        case_when(col1 == 1 ~ 4,
                  col1 == 2 ~ 3,
                  col1 == 3 ~ 1,
                  col1 == 4 ~ 0,
                  col1 == 5 ~ 2))

Thank you in advance.

You need to return() the value of data or not assign the result of the mutate() to data so that the result is returned by the function.

library(tidyverse)
Recode01 <- function(data, varname) {
  varname = enquo(varname)
  data <- data %>%
    mutate((!!varname) :=
             case_when((!!varname) == 1 ~ 4,
                       (!!varname) == 2 ~ 3,
                       (!!varname) == 3 ~ 1,
                       (!!varname) == 4 ~ 0,
                       (!!varname) == 5 ~ 2))
  return(data)
  
}

col1 <- c(1:5)
df1 <- as.data.frame(col1)
Recode01(df1, col1)
#>   col1
#> 1    4
#> 2    3
#> 3    1
#> 4    0
#> 5    2

Recode02 <- function(data, varname) {
  varname = enquo(varname)
  data %>%
    mutate((!!varname) :=
             case_when((!!varname) == 1 ~ 4,
                       (!!varname) == 2 ~ 3,
                       (!!varname) == 3 ~ 1,
                       (!!varname) == 4 ~ 0,
                       (!!varname) == 5 ~ 2))
  
}
Recode02(df1, col1)
#>   col1
#> 1    4
#> 2    3
#> 3    1
#> 4    0
#> 5    2

Created on 2024-03-02 with reprex v2.0.2

1 Like

Duh! Thank you. I had tried return(!!varname) but that didn't do it. Again, thanks. I do like this language after many years of SAS coding.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.