Make list of vectors by joining pair-corresponding

2019-01-26 07:40发布

问题:

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?

回答1:

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) ).



标签: r list vector