Skip to content

Instantly share code, notes, and snippets.

@matt-dray
Last active September 5, 2019 14:41
Show Gist options
  • Save matt-dray/aeb1bff29724a63d749482a429040d33 to your computer and use it in GitHub Desktop.
Save matt-dray/aeb1bff29724a63d749482a429040d33 to your computer and use it in GitHub Desktop.
Expand c(1:3) and c(1, 2, 3) to c(1, 2, 2, 3, 3, 3) and c(1, 1, 2, 1, 2, 3) ready for purrr::map() functions in R
# This isn't optimal and there's probably
# a function that does all this already
# Packages
library(dplyr)
library(purrr)
library(tibble)
# Write function
get_expansion <- function(x, y) {
# x: number of categories
# y: number of pages
expand_df <-
# repeat the page number by the number of pages
data.frame(x = rep(x, y)) %>%
# consecutive ascending row numbers within each page number
group_by(x) %>% mutate(y = row_number()) %>% ungroup()
return(expand_df)
}
# Use function to create dataframe of page-category expansions
df <- get_expansion(c(1:5), sample(1:5, 5)) # made-up data
# Map the function over the two columns of data in the df dataframe.
# The columns have the same names as the arguments to get_expansion(),
# so you can just give pmap() the dataframe instead of supplying
# .x and .y separately. pmap_dbl() outputs to a numeric vector.
output <- pmap_dbl(df, ~ .x + .y)
# Add the numeric vector result to the original dataframe as a new column
bind_cols(df, as.data.frame(output))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment