Reputation: 5155
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
?
Upvotes: 12
Views: 3161
Reputation: 59970
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)
).
Upvotes: 14