rpurrr

using purrr instead of for loop and updating object recursively


Given a data frame such as the following:

dat <- data.frame(
     plotType = c("RP", "FP"),
     turbType = c("3;8", "5;7"),
     turbSize = c(2.4, "3.6;4.2"),
     estimate = c(0.1, 0.5)
   )

I need to call tidyr::separate_longer_delim recursively for each column in:

strat <- c('turbType', 'turbSize')

This for loop achieves my goal but I was wondering if there was a purrr solution? Maybe with reduce()?

for(i in seq(length(strat))) {
     dat <- tidyr::separate_longer_delim(dat, dplyr::all_of(strat[i]), delim = ";")
   }

Thank you.


Solution

  • 1) Using Reduce

    library(tidyr)
    
    f <- function(x, y) separate_longer_delim(x, all_of(y), delim = ";")
    Reduce(f, strat, init = dat)
    

    2) or with purrr and f from above:

    library(purrr)
    library(tidyr)
    
    reduce(strat, f, .init = dat)