Skip to content

Instantly share code, notes, and snippets.

@infrahumano
Last active November 5, 2017 10:47
Show Gist options
  • Save infrahumano/9c817c382f39f1b2af195d9684e99d25 to your computer and use it in GitHub Desktop.
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.
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
@baptiste
Copy link

baptiste commented Nov 4, 2017

I usually go for plyr::mdply but never found a really satisfying tidyverse equivalent. Here's what I've settled on,

df <- data_frame(n=c(2, 3, 5), lambda=c(0.5, 0.1, 0.7))
df %>% 
  mutate(results = pmap(., .f = rpois)) %>% 
  unnest()

@paleolimbot
Copy link

Not tidyverse, but expand.grid() ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment