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
?
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.
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.
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)
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With