You can use indexing, if you index a number beyond the size of the object it returns NA
. This works for any arbitrary number of rows defined with foo
:
nm <- list(1:8,3:8,1:5)
foo <- 8
sapply(nm, '[', 1:foo)
EDIT:
Or in one line using the largest vector as number of rows:
sapply(nm, '[', seq(max(sapply(nm,length))))
From R 3.2.0
you may use lengths
(“get the length of each element of a list”) instead of sapply(nm, length)
:
sapply(nm, '[', seq(max(lengths(nm))))