8

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.

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?

7 Answers7

9

One option with Map from base R

do.call(Map, c(f = c, asdf))
akrun
  • 874,273
  • 37
  • 540
  • 662
7

An option using 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 
markus
  • 25,843
  • 5
  • 39
  • 58
5

A solution using the purrr package.

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
www
  • 38,575
  • 12
  • 48
  • 84
3
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
G5W
  • 36,531
  • 10
  • 47
  • 80
2

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
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
1

Package collapse has t_list for "Efficient List Transpose"

collapse::t_list(asdf)
# $V1
# [1]  1 10
#
# $V2
# [1]  2 20
#
# $V3
# [1]  3 30
#
# $V4
# [1]  4 40
# 
# $V5
# [1]  5 50
Henrik
  • 65,555
  • 14
  • 143
  • 159
0

With sapply and asplit:

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
Maël
  • 45,206
  • 3
  • 29
  • 67