How can I reshape a list of list from wide to long

只谈情不闲聊 提交于 2020-01-02 07:06:15

问题


I have a list of list with common structure

require(data.table)
l <- list(a1 = list(b=data.table(rnorm(3)), c=data.table(rnorm(3)), d=data.table(rnorm(3))),
          a2 = list(b=data.table(rnorm(3)), c=data.table(rnorm(3)), d=data.table(rnorm(3))))

Sometimes it is easier for lapply to change the structure to go from a 2x3 list to a 3x2 list like:

+a1---b         +b---a1
   ---c           ---a2
   ---d         +c---a1
+a2---b    to     ---a2
   ---c         +d---a1
   ---d           ---a2

Is there an idiomatic way to do this ?

Can it be done without copying over all the tables (that may be very big) ?


回答1:


I think purrr::transpose() is what you are looking for.

(ll = purrr::transpose(l))
# $b
# $b$a1
#            V1
# 1: -0.9615584
# 2: -0.8849469
# 3:  0.4831375
# 
# $b$a2
#            V1
# 1:  0.4634884
# 2: -0.7079083
# 3: -0.4366986
# 
# 
# $c
# $c$a1
#            V1
# 1:  0.4710617
# 2: -0.4927592
# 3: -1.3484420
# 
# $c$a2
#            V1
# 1: -0.4547821
# 2:  0.5752723
# 3:  0.6272826
# 
# 
# $d
# $d$a1
#             V1
# 1:  0.80827129
# 2: -0.03640465
# 3: -1.89417912
# 
# $d$a2
#            V1
# 1:  0.1844341
# 2:  0.4557670
# 3: -0.5714462

Checking the dimensions:

length(ll)
# [1] 3
sapply(ll, length)
# b c d 
# 2 2 2 

It looks like its implemented in C so my guess is efficiency is fairly well-optimized and unnecessary copying is minimized.



来源:https://stackoverflow.com/questions/34643746/how-can-i-reshape-a-list-of-list-from-wide-to-long

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!