I have a function which takes multiple inputs and creates multiple outputs. For example:
example_fun = function(a,b){
x = a+b
y = a-b
return(list(x=x, y=y))
}
How can I use dplyr::mutate to evaluate this function on each row of a dataframe? Turn
df = expand.grid(a=c(7,8), b=c(9,10))
df
a b
1 7 9
2 8 9
3 7 10
4 8 10
into
a b x y
1 7 9 16 -2
2 8 9 17 -1
3 7 10 17 -3
4 8 10 18 -2
this following code almost accomplishes it:
df = df %>%
mutate(outputs = pmap(list(a,b), example_fun)) %>%
unnest()
df
a b outputs
1 7 9 16
2 7 9 -2
3 8 9 17
4 8 9 -1
5 7 10 17
6 7 10 -3
7 8 10 18
8 8 10 -2