Bach
Bach

Reputation: 6227

Turning a couple of vectors into a list of vectors

Suppose I have a collection of independent vectors, of the same length. For example,

x <- 1:10
y <- rep(NA, 10)

and I wish to turn them into a list whose length is that common length (10 in the given example), in which each element is a vector whose length is the number of independent vectors that were given. In my example, assuming output is the output object, I'd expect

> str(output)
List of 10
 $ : num [1:2] 1 NA
 ...

> output
[[1]]
[1]  1 NA
...

What's the common method of doing that?

Upvotes: 1

Views: 59

Answers (3)

Ramnath
Ramnath

Reputation: 55735

Here is a solution that allows you to zip arbitrary number of equi-length vectors into a list, based on position of the element

merge_by_pos <- function(...){
  dotlist = list(...)
  lapply(seq_along(dotlist), function(i){
    Reduce('c', lapply(dotlist, '[[', i))
  })
}
x <- 1:10
y <- rep(NA, 10)
z <- 21:30

merge_by_pos(x, y, z)

Upvotes: 1

BrodieG
BrodieG

Reputation: 52697

Another option:

split(cbind(x, y), seq(length(x)))

or even:

split(c(x, y), seq(length(x)))

or even (assuming x has no duplicate values as in your example):

split(c(x, y), x)

Upvotes: 1

Ricardo Saporta
Ricardo Saporta

Reputation: 55420

use mapply and c:

 mapply(c, x, y, SIMPLIFY=FALSE)

[[1]]
[1]  1 NA

[[2]]
[1]  2 NA

..<cropped>..

[[10]]
[1] 10 NA

Upvotes: 4

Related Questions