Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write custom pipe-friendly functions?

Tags:

r

magrittr

I'm trying to create pipe-friendly functions using magrittr

For example, I tried to write a custom function to calculate the mean of a column:

library(magrittr)
custom_function <-
  function(.data, x) {
   mean(.data$x)
  }

mtcars %>%
 custom_function(mpg)

But I'm getting this error:

Error in (function(x, i, exact) if (is.matrix(i)) as.matrix(x)[[i]] else .subset2(x,  : 
  object 'mpg' not found

Maybe my reference to the variable is not working. How do I fix this .data$x ?

like image 545
writer_typer Avatar asked Sep 01 '25 20:09

writer_typer


1 Answers

.data$x does not refer to a column whose name is held in a variable x but refers to a column called "x". Use .data[[x]] to refer to the column whose name is the character string held in variable x and call your function using character string "mpg".

library(magrittr)
custom_function <- function(.data, x) mean(.data[[x]])

mtcars %>% custom_function("mpg")
## [1] 20.09062
like image 105
G. Grothendieck Avatar answered Sep 05 '25 04:09

G. Grothendieck