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 ?
.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With