I am trying to set up a customized function with multiple inputs and multiple return values, and using this function with purrr::map
on a data frame.
my sample data is:
test_data <-
tibble(x1 = 1:10,
x2 = 2:11,
x3 = 3:12,
x4 = x1 + x2 + x3)
this test_data
looks like this:
# A tibble: 10 x 4
x1 x2 x3 x4
<int> <int> <int> <int>
1 1 2 3 6
2 2 3 4 9
3 3 4 5 12
4 4 5 6 15
5 5 6 7 18
6 6 7 8 21
7 7 8 9 24
8 8 9 10 27
9 9 10 11 30
10 10 11 12 33
Firstly, if my function only has one return value (output_3
in this case):
my_function_1 <-
function(var1, var2, var3, var4){
output_1 <- var1 + var2
output_2 <- var2 + var3
output_3 <- var1 + var2 + var3
output_4 <- var1 + var2 + var4
return(output_3)
}
I cam pmap
this function using
my_results <-
dplyr::as.tbl(test_data) %>%
dplyr::mutate(output = purrr::pmap(list(var1 = x1, var2 = x2, var3 = x3, var4 = x4),
my_function_1)) %>%
tidyr::unnest()
the results looks like this:
my_results
# A tibble: 10 x 5
x1 x2 x3 x4 output
<int> <int> <int> <int> <int>
1 1 2 3 6 6
2 2 3 4 9 9
3 3 4 5 12 12
4 4 5 6 15 15
5 5 6 7 18 18
6 6 7 8 21 21
7 7 8 9 24 24
8 8 9 10 27 27
9 9 10 11 30 30
10 10 11 12 33 33
Now if my function has more than one return values, like
my_function_2 <-
function(var1, var2, var3, var4){
output_1 <- var1 + var2
output_2 <- var2 + var3
output_3 <- var1 + var2 + var3
output_4 <- var1 + var2 + var4
return(list(output_1, output_2, output_3, output_4))
}
How should I map this my_function_2
with purrr::map
and add return columns to test_data
, just like previous step with one return value?
I am also thinking to only have output results first (using the following code), and then join/bind
with test_data
:
pmap(list(test_data$x1,
test_data$x2,
test_data$x3,
test_data$x4),
my_function_2) %>%
flatten()
But the results is not in wanted format, like the following:
[[1]]
[1] 3
[[2]]
[1] 5
[[3]]
[1] 6
[[4]]
[1] 9
[[5]]
[1] 5
... ...
Could anybody remind me some potential solution to format the outputs and join with original test_data
?