Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add NAs to make all list elements equal length

Tags:

r

dplyr

tidyr

I'm doing a series of things in dplyr, tidyr, so would like to keep with a piped solution if possible.

I have a list with uneven numbers of elements in each component:

lolz <- list(a = c(2,4,5,2,3), b = c(3,3,2), c=c(1,1,2,4,5,3,3), d=c(1,2,3,1), e=c(5,4,2,2))
lolz
$a
[1] 2 4 5 2 3

$b
[1] 3 3 2

$c
[1] 1 1 2 4 5 3 3

$d
[1] 1 2 3 1

$e
[1] 5 4 2 2

I am wondering if there's a neat one liner to fill up each element with NAs such that they all are of the same length as the element with the maximum items:

I have a 2 liner:

lolz %>% lapply(length) %>% unlist %>% max -> mymax
lolz %>% lapply(function(x) c(x, rep(NA, mymax-length(x))))


$a
[1]  2  4  5  2  3 NA NA

$b
[1]  3  3  2 NA NA NA NA

$c
[1] 1 1 2 4 5 3 3

$d
[1]  1  2  3  1 NA NA NA

$e
[1]  5  4  2  2 NA NA NA

Wondering if I'm missing something quicker / more elegant.

like image 803
jalapic Avatar asked Jan 02 '16 21:01

jalapic


1 Answers

You could use

lapply(lolz, `length<-`, max(lengths(lolz)))
# $a
# [1]  2  4  5  2  3 NA NA
# 
# $b
# [1]  3  3  2 NA NA NA NA
# 
# $c
# [1] 1 1 2 4 5 3 3
# 
# $d
# [1]  1  2  3  1 NA NA NA
# 
# $e
# [1]  5  4  2  2 NA NA NA

or

n <- max(lengths(lolz))
lapply(lolz, `length<-`, n)
like image 81
lukeA Avatar answered Nov 02 '22 11:11

lukeA