Last active
November 5, 2017 10:47
-
-
Save infrahumano/9c817c382f39f1b2af195d9684e99d25 to your computer and use it in GitHub Desktop.
Is there a way of doing this within the tidyverse? I do not want to reinvent gunpowder.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(dplyr) | |
explode <- function(df, f) { | |
df_indexed <- df %>% mutate (explosion_index=1:n()) | |
f_indexed <- function(row_indexed) { | |
return(f(row_indexed) %>% mutate(explosion_index=row_indexed['explosion_index'])) | |
} | |
expansion <- df_indexed %>% apply(1, f_indexed) %>% do.call(rbind, .) | |
explosion <- df_indexed %>% | |
left_join(expansion, by='explosion_index') %>% | |
select(-explosion_index) | |
return(explosion) | |
} | |
f <- function(row){ | |
return(data_frame(sample_index=1:row['sample_size'], | |
sample_value=rpois(row['sample_size'], | |
row['lambda']))) | |
} | |
df <- data_frame(sample_size=c(2, 3, 5), lambda=c(0.5, 0.1, 0.7)) | |
df %>% explode(f) | |
# A tibble: 10 x 4 | |
# sample_size lambda sample_index sample_value | |
# <dbl> <dbl> <int> <int> | |
# 1 2 0.5 1 1 | |
# 2 2 0.5 2 1 | |
# 3 3 0.1 1 0 | |
# 4 3 0.1 2 0 | |
# 5 3 0.1 3 0 | |
# 6 5 0.7 1 1 | |
# 7 5 0.7 2 3 | |
# 8 5 0.7 3 0 | |
# 9 5 0.7 4 1 | |
# 10 5 0.7 5 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not tidyverse, but
expand.grid()
?