如何“转置”向量列表?

7 transpose r list

我有一个向量列表:

asdf = list(c(1, 2, 3, 4, 5), c(10, 20, 30, 40, 50))
Run Code Online (Sandbox Code Playgroud)

现在我想“转置”它,即获得5对的列表而不是5对的列表。

更具体地说,我希望结果类似于键入的结果:

transposedAsdf = list(c(1, 10), c(2, 20), c(3, 30), c(4, 40), c(5, 50))
Run Code Online (Sandbox Code Playgroud)

但我不知道如何实现这一目标。如何?

akr*_*run 8

一种选择Mapfrombase R

do.call(Map, c(f = c, asdf))
Run Code Online (Sandbox Code Playgroud)


mar*_*kus 6

一个选项使用 data.table

data.table::transpose(asdf)
#[[1]]
#[1]  1 10

#[[2]]
#[1]  2 20

#[[3]]
#[1]  3 30

#[[4]]
#[1]  4 40

#[[5]]
#[1]  5 50 
Run Code Online (Sandbox Code Playgroud)


www*_*www 5

使用purrr包的解决方案。

library(purrr)

asdf2 <- transpose(asdf) %>% map(unlist)
asdf2
# [[1]]
# [1]  1 10
# 
# [[2]]
# [1]  2 20
# 
# [[3]]
# [1]  3 30
# 
# [[4]]
# [1]  4 40
# 
# [[5]]
# [1]  5 50
Run Code Online (Sandbox Code Playgroud)


Gre*_*gor 2

这是一种方法:

split(do.call(cbind, asdf), 1:length(asdf[[1]]))
# $`1`
# [1]  1 10
# 
# $`2`
# [1]  2 20
# 
# $`3`
# [1]  3 30
# 
# $`4`
# [1]  4 40
# 
# $`5`
# [1]  5 50
Run Code Online (Sandbox Code Playgroud)