Home > Enterprise >  Define custom function on-the-fly in dplyr::mutate_at() function
Define custom function on-the-fly in dplyr::mutate_at() function

Time:10-11

I was to use dplyr::mutate_at() to change values of certain columns in a data.frame using some custom defined function. Below are my code :

library(dplyr)
data(iris)
iris %>% mutate_at('Sepal.Length', ~ function(x1 = ., x2 = 100) return(x1   x2))

With this I am getting below error :

Error: Problem with `mutate()` column `Sepal.Length`.
ℹ `Sepal.Length = (structure(function (..., .x = ..1, .y = ..2, . = ..1) ...`.
✖ `Sepal.Length` must be a vector, not a function.

I want to define my custom function just within the dplyr::mutate_at() only.

Could you please help me to understand why I am getting this error?

CodePudding user response:

You don't need the ~ when you use the function() keyword:

iris %>% mutate_at('Sepal.Length', function(x1 = ., x2 = 100) return(x1 x2))

> iris %>% mutate_at('Sepal.Length', function(x1 = ., x2 = 100) return(x1   x2))
    Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
1          105.1         3.5          1.4         0.2     setosa
2          104.9         3.0          1.4         0.2     setosa
3          104.7         3.2          1.3         0.2     setosa
4          104.6         3.1          1.5         0.2     setosa
  • Related