lets say I have a tibble which looks like this:
library(tidyverse)
tib <- tibble (a = 1:3, b = 4:6, d = -1:1)
I want to add a column to this tibble where each entry is a function with parameters a,b and d (like f(x) = ax^2 + bx +d). This would mean that (e.g) in the first row I would like to add the function f(x) = 1 x ^2 + 4 x -1, and so on.
I tried the following:
tib2 <- tib %>%
mutate(fun = list(function(x) {a*x^2+b*x+d}))
This does not work since the functions do not know what a, b and d are.
I managed to build a work-around solution using the function mapply
lf <- mapply(function(a,b,d){return(function(x){a*x^2 + b*x + d})}, tib$a, tib$b, tib$d)
tib3 <- tib %>%
add_column(lf)
I was wondering if anyone knows a more elegant way of doing this within the tidyverse. It feels like there is a way using the map function from the purrr package, but I did not manage to get it working.
Thank you
x
? intib %>% mutate(fun = list(function(x) {a*x^2+b*x+d}))
you're passing the whole tibble as an argument, so you expect tibble$a to be multiplied by tibble-squared, etc? – lebatsnokfun <- function(x, df=tib) with(df, a*x^2 + b*x + d)
... so fun(1) will return4 7 10
etc. Is the idea of attaching a function like this to the tibble? So that would calculate the result each time, istead of storing the result in a static column? – lebatsnok