I have written the code below to take two dataframes and interweave them by row based on this example. I believe this is using Bresenham's line algorithm which evenly disperses the shorter dataframe within the longer one.
interleave_rows <- function(x, y) {
m <- nrow(x)
yi <- 1
len <- m + nrow(y)
err <- len %/% 2
res <- x
for (i in 1:len) {
err <- err - m
if (err < 0) { err <- err + len } else {
res <- add_row(res, !!! slice(y, yi), .before = i)
yi <- yi + 1
}
}
res
}
l <- list(
a = tibble(n = 1:3, l = letters[1:3]),
b = tibble(n = 4:9, l = letters[4:9]),
c = tibble(n = 10:11, l = letters[10:11])
)
reduce(l, interleave_rows)
I'm using this in a shiny app as part of a reduce and it's a little slow. I also don't find this to be a very tidy or functional approach to solving this problem. I haven't been able to wrap my head around how to do this without the loop and reassigning variables but I suspect doing so would be faster. Is there a better approach?