Reputation: 64004
I have the following functions that returns a tibble:
library(tidyverse)
process_data <- function(ky1 = "a", ky2 = "x") {
l <- list( musician = c("John","Paul","George","Ringo"),
tools = c("voice", "guitar", "bass", "drum")
)
df <- as.tibble(l) %>%
mutate(first_key = ky1,second_key = ky2)
return(df)
}
process_data()
#> # A tibble: 4 × 4
#> musician tools first_key second_key
#> <chr> <chr> <chr> <chr>
#> 1 John voice a x
#> 2 Paul guitar a x
#> 3 George bass a x
#> 4 Ringo drum a x
Given two vectors
ky1_vec <- c("a","b","c")
ky2_vec <- c("w","x","y","z")
I'd like to get one data frame/tibble for all combinations of
the above list using process_data()
:
musician tools first_key second_key
John voice a w
Paul guitar a w
George bass a w
Ringo drum a w
John voice a x
Paul guitar a x
George bass a x
Ringo drum a x
... ... ... ...
John voice c z
Paul guitar c z
George bass c z
Ringo drum c z
# total 3 * 4 * 4 = 48 rows
How can I do that?
Upvotes: 1
Views: 39
Reputation: 887128
We can use map2_df
library(tidyverse)
d1 <- crossing(ky1_vec, ky2_vec)
map2_df(d1$ky1_vec, d1$ky2_vec, process_data)
Or another option is
expand.grid(ky1_vec = ky1_vec, ky2_vec = ky2_vec) %>%
rowwise() %>%
do(data.frame(process_data(.$ky1_vec, .$ky2_vec)))
With this result:
Source: local data frame [48 x 4]
Groups: <by row>
# A tibble: 48 × 4
musician tools first_key second_key
* <chr> <chr> <fctr> <fctr>
1 John voice a w
2 Paul guitar a w
3 George bass a w
4 Ringo drum a w
5 John voice b w
6 Paul guitar b w
7 George bass b w
8 Ringo drum b w
9 John voice c w
10 Paul guitar c w
# ... with 38 more rows
Upvotes: 1