Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R dplyr::mutate - add all elements in a returned list

Tags:

r

dplyr

I have a function returning a list. I'm using mutate to add columns in a data frame that correspond to the output. The calculation is rather involved so I would prefer to only call the function once. I'm rather new to R and dplry and cannot figure out a more efficient way of doing this.

Here is a very simple example of what I am doing now.

library(dplyr)

testFun <- function(x,z)
{
  list(x2=x*x + z, x3=x*x*x + z)
}

have <- data.frame(x=seq(1:10),y=1,z=0)

want <- have %>%
        dplyr::mutate(x2=testFun(x,z)$x2,
                      x3=testFun(x,z)$x3)

How can I do this more efficiently?

like image 963
DomPazz Avatar asked Dec 05 '22 12:12

DomPazz


1 Answers

With the purrr-package you can solve this problem, like that:

library(purrr)
library(dplyr)

testFun <- function(x,z) {
  tibble(x2=x*x + z, x3=x*x*x + z)
}

have %>%
  mutate(new_x = map2(x, z, testFun)) %>% 
  unnest(new_x)

#     x y z  x2   x3
# 1   1 1 0   1    1
# 2   2 1 0   4    8
# 3   3 1 0   9   27
# 4   4 1 0  16   64
# 5   5 1 0  25  125
# 6   6 1 0  36  216
# 7   7 1 0  49  343
# 8   8 1 0  64  512
# 9   9 1 0  81  729
# 10 10 1 0 100 1000

Note that I changed the output of your function from a list to a tibble.

like image 52
kath Avatar answered Dec 24 '22 18:12

kath