简体   繁体   English

如何“转置”向量列表?

[英]How to "transpose" a list of vectors?

I have a list of vectors:我有一个向量列表:

asdf = list(c(1, 2, 3, 4, 5), c(10, 20, 30, 40, 50))

Now I want to "transpose" it, that is, obtain a list of 5 pairs instead of a pair of lists of 5.现在我想“转置”它,即获得一个 5 对的列表,而不是 5 对的列表。

To be more specific, I want the result to be analogous to the result of typing:更具体地说,我希望结果类似于键入的结果:

transposedAsdf = list(c(1, 10), c(2, 20), c(3, 30), c(4, 40), c(5, 50))

But I don't know how to achieve this.但我不知道如何实现这一点。 How to?如何?

transposedAsdf = as.list(as.data.frame(t(as.data.frame(asdf))))
transposedAsdf
$V1
[1]  1 10

$V2
[1]  2 20

$V3
[1]  3 30

$V4
[1]  4 40

$V5
[1]  5 50

An option using data.table 使用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 

A solution using the purrr package. 使用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

Here's one way: 这是一种方式:

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

base RMap一个选项

do.call(Map, c(f = c, asdf))

Package collapse has t_list for "Efficient List Transpose"collapse具有用于“高效列表转置”的t_list

collapse::t_list(asdf)
# $V1
# [1]  1 10
#
# $V2
# [1]  2 20
#
# $V3
# [1]  3 30
#
# $V4
# [1]  4 40
# 
# $V5
# [1]  5 50

With sapply and asplit :使用sapplyasplit

asplit(sapply(asdf, `[`, 1:5), 1)
[[1]]
[1]  1 10

[[2]]
[1]  2 20

[[3]]
[1]  3 30

[[4]]
[1]  4 40

[[5]]
[1]  5 50

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM