Omry Atia
Omry Atia

Reputation: 2443

bind specific elements of a list

I have a list containing elements of different lengths. I would like to bind together elements having length of less than L, and replace the individual short elements with the united element.

For example:

L = list()
for (i in 1:3) {
    L[[i]] = seq(1:i)
}

I would like to unite elements 1,2 into element "12" containing the numbers 1,1,2 instead of the first two elements. How can I do this systematically (in a loop, or vectorially)?

The desired result is: first element c(1,1,2), second element c(1,2,3)

Upvotes: 2

Views: 147

Answers (2)

akrun
akrun

Reputation: 887391

We get the max length of the list ('L'), get a logical index by comparing with the lengths, concatenate those elements are not matching the max length and append with the other list element

i1 <- max(lengths(L))
i2 <- i1 != lengths(L)
c(list(Reduce(`c`, L[i2])), L[!i2])
#[[1]]
#[1] 1 1 2

#[[2]]
#[1] 1 2 3

Upvotes: 1

Julius Vainora
Julius Vainora

Reputation: 48211

We may do

c(list(unlist(L[lengths(L) < 3])), L[lengths(L) >= 3])
# [[1]]
# [1] 1 1 2
#
# [[2]]
# [1] 1 2 3

The second part, L[lengths(L) >= 3], contains all the long enough elements of L. Then L[lengths(L) < 3] is the list of all the short elements of L, and unlist combines them together.

Upvotes: 2

Related Questions