0

Let's consider list following:

lst <- list((c("A")), (c("B")), (c("A", "B")), (c("A", "B", "C")))

The first and second element of the list contain one element, third contain two elements, and last one contains three elements. What I want to do is to fill each element with NA's so that every element will have same length. i.e.

now we have:

 lst
[[1]]
[1] "A"

[[2]]
[1] "B"

[[3]]
[1] "A" "B"

[[4]]
[1] "A" "B" "C"

I want to have:

 lst
[[1]]
[1] "A" NA NA 

[[2]]
[1] "B" NA NA 

[[3]]
[1] "A" "B" NA

[[4]]
[1] "A" "B" "C"

my first idea was of course to use rep combined with lapply. So:

lapply(lst, function(x) rep(NA, 3 - length(x)))

However it seems that my understanding of lapply function is not as it is working. Could you please give me a hand to approach the solution of this problem ?

John
  • 1,849
  • 2
  • 13
  • 23

1 Answers1

0

1) Use length<- and lengths as follows:

lapply(lst, "length<-", max(lengths(lst)))

giving:

[[1]]
[1] "A" NA  NA 

[[2]]
[1] "B" NA  NA 

[[3]]
[1] "A" "B" NA 

[[4]]
[1] "A" "B" "C"

2) Another approach is to convert each component to a ts series as those can be cbind'ed even without the same length and then convert back to an unnamed list of plain vectors. This approach only works if the components are of the same type which is the case in the question's example.

unname(lapply(do.call("cbind", lapply(lst, ts)), as.vector))
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341