Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a uneven list to a data.frame [duplicate]

Tags:

dataframe

r

In a simple situation, converting an even list to a data frame can be done by as.data.frame(). For example :

> (x1 <- list(a = 1:3, b = 4:6, c = 7:9))
> as.data.frame(x1)

#   a b c
# 1 1 4 7
# 2 2 5 8
# 3 3 6 9

However, if the lengths of components in a list are not equal, then as.data.frame() doesn't work.

> (x2 <- list(a = 1:4, b = 5:6, c = 7:11, d = 12:14))

# $a
# [1] 1 2 3 4
# $b
# [1] 5 6
# $c
# [1]  7  8  9 10 11
# $d
# [1] 12 13 14

> as.data.frame(x2) # get an error

I want to achieve two goals. One is :

#    a  b  c  d
# 1  1  5  7 12
# 2  2  6  8 13
# 3  3 NA  9 14
# 4  4 NA 10 NA
# 5 NA NA 11 NA

And the other is :

#   V1 V2 V3 V4 V5
# a  1  2  3  4 NA
# b  5  6 NA NA NA
# c  7  8  9 10 11
# d 12 13 14 NA NA

I know there are some functions or base methods especially for these two cases. Please give me a little help.

like image 293
Darren Tsai Avatar asked Dec 08 '18 15:12

Darren Tsai


1 Answers

A solution using the tidyverse.

library(tidyverse)

x3 <- map_dfr(x2, ~as_data_frame(t(.)))
x3
# # A tibble: 4 x 5
#      V1    V2    V3    V4    V5
#   <int> <int> <int> <int> <int>
# 1     1     2     3     4    NA
# 2     5     6    NA    NA    NA
# 3     7     8     9    10    11
# 4    12    13    14    NA    NA

x4 <- as_data_frame(t(x3))
x4
# # A tibble: 5 x 4
#      V1    V2    V3    V4
#   <int> <int> <int> <int>
# 1     1     5     7    12
# 2     2     6     8    13
# 3     3    NA     9    14
# 4     4    NA    10    NA
# 5    NA    NA    11    NA
like image 170
www Avatar answered Sep 30 '22 09:09

www