0

I've seen several variations of this question on the site, but not this particular problem.

I have created an unnamed list of numeric vectors. Each vector is varying in length. For example, the first few entries might look like:

data[[1]]
1 2 3

data[[2]]
1 2 3 4

data[[3]]
1 3

I am trying to export this into a table format, so I am trying to convert it to a dataframe that looks something like:

1  2  3  NA
1  2  3  4
1  3  NA NA

I've tried various methods like do.call, rbindlist and as.data.frame. I've also tried creating my dataset as a list of lists instead of a list of vectors.

Thank you for any suggestions.

Nikhil P
  • 31
  • 5

3 Answers3

1

With tidyverse:

l <- list(c(1,2,3,4),c(1,2,3),c(1,3))
data.frame(x=I(l)) %>% 
  mutate(id=row_number()) %>% 
  unnest %>% 
  group_by(id) %>% mutate(k=paste0("V",row_number())) %>% 
  spread(k,x) %>% select(-id)
#     V1    V2    V3    V4
#  <dbl> <dbl> <dbl> <dbl>
#1     1     2     3     4
#2     1     2     3    NA
#3     1     3    NA    NA
Nicolas2
  • 2,170
  • 1
  • 6
  • 15
0

Place the list in a nested data frame. Add a row index i for each vector in the list, unnest the data frame. Give a column index j for each element in each vector, spread the data in wide format.

library(tidyverse)
l <- list(c(1,2,3),c(1,2,3,4),c(1,3))
data_frame(data = l) %>%
    mutate(i = row_number()) %>% 
    unnest() %>% 
    group_by(i) %>% 
    mutate(j = paste0("x", 1:n())) %>% 
    spread(j, data)
# A tibble: 3 x 5
# Groups:   i [3]
i    x1    x2    x3    x4
* <int> <dbl> <dbl> <dbl> <dbl>
1     1     1     2     3    NA
2     2     1     2     3     4
3     3     1     3    NA    NA
Paul Rougieux
  • 10,289
  • 4
  • 68
  • 110
0

Nicola's answer works like a charm and is the simplest I've seen so far. Thank you!

do.call(rbind,lapply(data,function(x) "length<-"(x,max(lengths(data)))))
Nikhil P
  • 31
  • 5