在 R 中将列表转换为数据帧

Eth*_*han 6 r list dataframe

所以我有一个清单,说:

L1 <- list(1:10, 5:14, 10:19)
Run Code Online (Sandbox Code Playgroud)

现在我试图将列表的输出作为数据帧,以便我的输出看起来:

 1. 1  2  3  4  5  6  7  8  9 10
 2. 5  6  7  8  9 10 11 12 13 14
 3. 10 11 12 13 14 15 16 17 18 19
Run Code Online (Sandbox Code Playgroud)

我在用

as.data.frame(L1, row.names = TRUE)
Run Code Online (Sandbox Code Playgroud)

list_vect2df(L1)
Run Code Online (Sandbox Code Playgroud)

但他们都没有给出所需的输出

www*_*www 5

这是一个使用包中的tas.data.frame、 和 的想法。map_dfr

L1 <- list(1:10, 5:14, 10:19)

library(purrr)

map_dfr(L1, ~as.data.frame(t(.x)))
#   V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
# 1  1  2  3  4  5  6  7  8  9  10
# 2  5  6  7  8  9 10 11 12 13  14
# 3 10 11 12 13 14 15 16 17 18  19
Run Code Online (Sandbox Code Playgroud)

相同的想法,但完全基于 R 基础。

do.call(rbind, lapply(L1, function(x) as.data.frame(t(x))))
#   V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
# 1  1  2  3  4  5  6  7  8  9  10
# 2  5  6  7  8  9 10 11 12 13  14
# 3 10 11 12 13 14 15 16 17 18  19
Run Code Online (Sandbox Code Playgroud)

另一个使用as.data.frame两次的基本 R 想法。我们可以稍后更改行名称。

as.data.frame(t(as.data.frame(L1)))
#        V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
# X1.10   1  2  3  4  5  6  7  8  9  10
# X5.14   5  6  7  8  9 10 11 12 13  14
# X10.19 10 11 12 13 14 15 16 17 18  19
Run Code Online (Sandbox Code Playgroud)

最后,同样的想法,但使用transpose中的函数。

data.table::transpose(as.data.frame(L1))
#   V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
# 1  1  2  3  4  5  6  7  8  9  10
# 2  5  6  7  8  9 10 11 12 13  14
# 3 10 11 12 13 14 15 16 17 18  19
Run Code Online (Sandbox Code Playgroud)


Moo*_*per 5

您可以unlist并使用matrix,然后转换为data.frame. 对于这种情况来说似乎更快。

as.data.frame(matrix(unlist(L1),nrow=length(L1),byrow=TRUE)

microbenchmark::microbenchmark(
a= map_dfr(L1, ~as.data.frame(t(.x))),
b= do.call(rbind, lapply(L1, function(x) as.data.frame(t(x)))),
c= as.data.frame(t(as.data.frame(L1))),
d= data.table::transpose(as.data.frame(L1)),
e= as.data.frame(matrix(unlist(L1),nrow=length(L1),byrow=TRUE)),
times = 100,unit = "relative")

# Unit: relative
# expr       min        lq      mean    median        uq       max neval
# a  9.146545  8.548656  8.859087  8.859051  9.449237  7.265274   100
# b 13.879833 11.523000 11.433790 10.924726 10.797251 24.012107   100
# c 12.719835 10.635809 10.442108 10.229913 10.259789  7.020377   100
# d 10.439881  9.143530  9.205734  8.859026  9.176125  6.624454   100
# e  1.000000  1.000000  1.000000  1.000000  1.000000  1.000000   100
Run Code Online (Sandbox Code Playgroud)