Home > Software design >  Custom Function Mutate that mutates column
Custom Function Mutate that mutates column

Time:06-13

I'm having trouble with a function that I'm trying to write. I'd like to be able to change the column via the function so that I can do some mutations inside of a pipe. I'm afraid my R is a bit rusty, so I would appreciate some help.

#  Create some fake data
dat <- data.frame(x = 1:4,
                  y = 5:8, 
                  z = 9:12)


# Write the function
my_func <- function(data, col1, number){
  x <- data %>% 
    # This is where I run into trouble
    mutate(col4 = [[col1]]   number)
  
  return(x)
}

# Try to call the function - gets error
df <- my_func(dat, x, 5)

I've tried all sorts of stuff with this, but nothing works or even gets close.

CodePudding user response:

Use curly-curly operator ({{}}) if we are passing unquoted column name

my_func <- function(data, col1, number){
  x <- data %>% 
    
    mutate(col4 = {{col1}}   number)
  
  return(x)
}

-testing

> my_func(dat, x, 5)
  x y  z col4
1 1 5  9    6
2 2 6 10    7
3 3 7 11    8
4 4 8 12    9

For more flexibility i.e. using either quoted or unquoted, convert to symbol with ensym and evaluate (!!)

my_func <- function(data, col1, number){
  x <- data %>% 
    mutate(col4 = !! rlang::ensym(col1)   number)
  return(x)
}

-testing

> my_func(dat, "x", 5)
  x y  z col4
1 1 5  9    6
2 2 6 10    7
3 3 7 11    8
4 4 8 12    9
> my_func(dat, x, 5)
  x y  z col4
1 1 5  9    6
2 2 6 10    7
3 3 7 11    8
4 4 8 12    9
  • Related