Reputation: 2788
I am having difficulty getting my function names as headers in my final data frame after using purrr::pmap_dfc
.
My final code has V1
and V2
as headers, but I would like my function names, add_1_times_multi
and neg_1_times_multi
, as headers. Below is a reprex.
library(tidyverse)
# define functions
add_1_times_multi <- function(vec, multi){(vec + 1) * multi}
neg_1_times_multi <- function(vec, multi){-(vec) * multi}
# put functions in list
my_functions <- function(vec,multi){
list(
add_1_times_multi(vec, multi),
neg_1_times_multi(vec, multi)
)
}
# define values
my_vector <- rnorm(n = 10, mean = 100, sd = 1)
multiplyr <- 3
# put values in list
l <- list(list(my_vector), multiplyr)
# purrr::pmap_dfc
pmap_dfc(l, my_functions)
#> # A tibble: 10 x 2
#> V1 V2
#> <dbl> <dbl>
#> 1 308. -305.
#> 2 305. -302.
#> 3 304. -301.
#> 4 304. -301.
#> 5 310. -307.
#> 6 304. -301.
#> 7 298. -295.
#> 8 300. -297.
#> 9 301. -298.
#> 10 305. -302.
Created on 2018-12-06 by the reprex package (v0.2.1)
As stated above I would like the final result to have add_1_times_multi
and neg_1_times_multi
as column names. Not V1
and V2
.
Upvotes: 0
Views: 373
Reputation: 7437
Your way to define your function is quite tortuous. Instead of creating 2 functions, then a 3rd function which makes a list of those functions, why not directly create a function which gives you what you want:
my_function <- function(vec, multi) {
tibble(
add_1_times_multi = (vec + 1) * multi,
neg_1_times_multi = - vec * multi
)
}
Also, since you only have 2 vectors as arguments to your function, you don't need pmap()
and could simply use map2()
:
my_vector <- rnorm(n = 10, mean = 100, sd = 1)
multiplyr <- 3
map2_df(my_vector, multiplyr, my_function)
If you really want to use pmap()
:
l <- list(my_vector, multiplyr)
pmap_df(l, my_function)
Note that you don't need to pass my_vector
in list()
before passing it again in list()
with multiplyr
.
Upvotes: 3