Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make list of vectors by joining pair-corresponding elements of 2 vectors efficiently in R

Tags:

list

r

vector

I have 2 vectors:

v1 <- letters[1:5]
v2 <- as.character(1:5)

> v1
[1] "a" "b" "c" "d" "e"
> v2
[1] "1" "2" "3" "4" "5"

I want to create a list of length 5, which contains vectors of elements, consisting of two character values: value from v1 and value v2 from corresponding index number:

> list(c(v1[1], v2[1]),
+      c(v1[2], v2[2]),
+      c(v1[3], v2[3]),
+      c(v1[4], v2[4]),
+      c(v1[5], v2[5]))
[[1]]
[1] "a" "1"

[[2]]
[1] "b" "2"

[[3]]
[1] "c" "3"

[[4]]
[1] "d" "4"

[[5]]
[1] "e" "5"

How to do this efficiently in R?

like image 460
Marta Karas Avatar asked May 19 '14 08:05

Marta Karas


People also ask

Can you make a list of vectors in R?

A list is a recursive vector: a vector that can contain another vector or list in each of its elements. Lists are one of the most flexible data structures in R. As a result, they are used as a general purpose glue to hold objects together.

How do I make a vector list?

Convert Vector to List in R or create a list from vector can be done by using as. list() or list() functions. A Vector in R is a basic data structure consist elements of the same data type whereas an R List is an object consisting of heterogeneous elements meaning can contain elements of different types.


1 Answers

mapply(c, v1, v2, SIMPLIFY = FALSE)
#$a
#[1] "a" "1"

#$b
#[1] "b" "2"

#$c
#[1] "c" "3"

#$d
#[1] "d" "4"

#$e
#[1] "e" "5"

(OR more precisely with respect to your OP which returns an unnamed list use mapply(c, v1, v2, SIMPLIFY = FALSE, USE.NAMES = FALSE) ).

like image 83
Simon O'Hanlon Avatar answered Sep 28 '22 23:09

Simon O'Hanlon