Creating a named list from two vectors (names, values)

孤者浪人 提交于 2019-11-30 01:18:08
Ben Bolker

You can use setNames()

setNames(as.list(c(1, 2)), c("foo", "bar"))

(for a list) or

setNames(c(1, 2), c("foo", "bar"))

(for a vector)

joran

I share Ben's puzzlement about why you might want to do this, and his recommendation.

Just for curiosity's sake, there is a sort of "hidden" feature in mapply that will allow this:

x <- letters[1:2]
y <- 1:2
mapply(function(x,y) { y }, x, y, SIMPLIFY = FALSE,USE.NAMES = TRUE)
$a
[1] 1

$b
[1] 2

Noting that the documentation for USE.NAMES says:

USE.NAMES logical; use names if the first ... argument has names, or if it is a character vector, use that character vector as the names.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!