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.
Recognized by R Language Collective
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)
2
I would do it like this:
library(tidyr)
library(dplyr)
dat |>
mutate(id = row_number()) |>
separate_longer_delim(cols = c(turbType, turbSize), delim = ";") |>
group_by(id) |>
complete(turbType, turbSize) |>
fill(plotType, estimate, .direction = "downup") |>
ungroup()
# # A tibble: 6 × 5
# id turbType turbSize plotType estimate
# <int> <chr> <chr> <chr> <dbl>
# 1 1 3 2.4 RP 0.1
# 2 1 8 2.4 RP 0.1
# 3 2 5 3.6 FP 0.5
# 4 2 5 4.2 FP 0.5
# 5 2 7 3.6 FP 0.5
# 6 2 7 4.2 FP 0.5
1