Interleave Lists in R

Interleave lists in R

Here's one way:

idx <- order(c(seq_along(a), seq_along(b)))
unlist(c(a,b))[idx]

# [1] "a.1" "b.1" "a.2" "b.2" "a.3" "b.3" "b.4"

As @James points out, since you need a list back, you should do:

(c(a,b))[idx]

interleave list after every n elements

Here's the length of the new list

len = length(listi) + max(0, floor((length(listi) - 1) / 2))

and the index of the elements that should be the original values

idx = seq_len(len) %% 3 != 0

Use these to create a new list and insert the old and interstitial values

res = vector("list", len)
res[idx] = l
res[!idx] = list(v)

Package as a function for robustness and reuse.

fun = function(l, v, n = 2) {
## validate arguments
stopifnot(
is.numeric(n), length(n) == 1, !is.na(n),
is.list(l), is.vector(v)
)

## length and index for original values
len = length(l) + max(0, floor((length(l) - 1) / n))
idx = seq_len(len) %% (n + 1) != 0

## create and populate result
res = vector("list", len)
res[idx] = l
res[!idx] = list(v)
res
}

with

> str(fun(listi, interElem))
List of 11
$ : chr "a"
$ : num [1:2] 13 37
$ : chr [1:2] "inter" "leavistan"
$ : chr "b"
$ : num [1:2] 13 37
$ : chr [1:2] "inter" "leavistan"
$ : chr "c"
$ : num [1:2] 13 37
$ : chr [1:2] "inter" "leavistan"
$ : chr "d"
$ : num [1:2] 13 37

interleave nested ist of vectors in r with string padding based on max nchar in innermost nest

It should be convenient to elongate each element with a sufficient number of "" to conveniently find the maximum elementwise nchar and, later, rbind to interleave as in the linked post:

n = do.call(max, lapply(x, lengths))
x2 = lapply(x, function(ab) lapply(ab, function(x) c(x, rep_len("", n - length(x)))))

Then find the 'parallel' maximum nchar for each element:

ncx2 = lapply(x2, function(x) unlist(.mapply(max, lapply(x, nchar), NULL)))

and right-pad with spaces, accordingly:

x3 = Map(function(elt, nc) lapply(elt, function(x) sprintf("%-*s", nc, x)), x2, ncx2)

Finally, interleave the elements using the alternative of rbind and format the output appropriately:

.mapply(function(...) trimws(paste(c(rbind(...)), collapse = "")), x3, NULL)
#[[1]]
#[1] "11 000 11 00 111110 11100 11111111110000011 0011"
#
#[[2]]
#[1] "11 00 111100011 00111000011 0 111"
#
#[[3]]
#[1] "11110000000111 00 1111 00"

If x has, only, two elements, it could be more convenient to store a = x$A; b = x$B and duplicate parts of code to avoid the extra nested lapply/mapply compilcated calls.

interleave rows of matrix stored in a list in R

Here is a one-liner:

do.call(rbind, l)[order(sequence(sapply(l, nrow))), ]
# [,1] [,2]
# [1,] 1 3
# [2,] 5 7
# [3,] 2 4
# [4,] 6 8

To help understand, the matrices are first stacked on top of each other with do.call(rbind, l), then the rows are extracted in the right order:

sequence(sapply(l, nrow))
# a1 a2 b1 b2
# 1 2 1 2

order(sequence(sapply(l, nrow)))
# [1] 1 3 2 4

It will work with any number of matrices and it will do "the right thing" (subjective) even if they don't have the same number of rows.

Interleaving two data.frames of data.frames in R

We need to use Map for interleaveing corresponding elements of both lists

library(gdata)
out_lst <- Map(interleave, new_list, second_list)

Or another option is map2 from purrr

library(purrr)
out_lst <- map2(new_list, second_list, interleave)

How to interleave vectors in R according to a position indicator

Instead of iterating over positions, you can iterate over vectors:

i = character(length(pos))
for (p in 1:length(v)) i[ pos == p ] <- v[[p]]
# "a" "b" "1" "x" "2" "3" "y" "4" "c" "z" "5" "d"

The loop can also be avoided here:

i = character(length(pos))
i[ order(pos) ] <- c(v1,v2,v3)
# "a" "b" "1" "x" "2" "3" "y" "4" "c" "z" "5" "d"

For reference, I looked at this other nice question on interleaving.

How to interleave two string vectors with equal signs?

The coefplot documentation describes newNames as a "Named character vector of new names for coefficients"

# b is a character vector without names
b <- c('clean_name1', 'clean_name2')

# give it names
a <- c('coef_name1', 'coef_name2')
names(b) <- a
# now b is a named character vector

# so this should work
coefplot::coefplot(model, newNames = b, intercept = FALSE)

Prolog How can I construct a list of list into a single list by interleaving?

Instead of thinking about efficiency first, we can think about correctness first of all.

interleaving_join( [[]|X], Y):- 
interleaving_join( X, Y).

that much is clear, but what else?

interleaving_join( [[H|T]|X],         [H|Y]):- 
append( X, [T], X2),
interleaving_join( X2, Y).

But when does it end? When there's nothing more there:

interleaving_join( [], []).

Indeed,

2 ?- interleaving_join([[1,2],[3,4]], Y).
Y = [1, 3, 2, 4] ;
false.

4 ?- interleaving_join([[1,4],[2,5],[3,6,7]], X).
X = [1, 2, 3, 4, 5, 6, 7] ;
false.

This assumes we only want to join the lists inside the list, whatever the elements are, like [[...],[...]] --> [...]. In particular, we don't care whether the elements might themselves be lists, or not.

It might sometimes be interesting to collect all the non-list elements in the inner lists, however deeply nested, into one list (without nesting structure). In fact such lists are actually trees, and that is known as flattening, or collecting the tree's fringe. It is a different problem.



Related Topics



Leave a reply



Submit