从两个向量(名称、值)创建命名列表 [英] Creating a named list from two vectors (names, values)
问题描述
有没有办法在两个向量上使用 mapply 来构造命名列表?第一个向量的类型为 character
并包含用于列表的名称,而第二个包含值.
Is there a way to use mapply on two vectors to construct a named list? The first vector would be of type character
and contain the names used for the list while the second contains the values.
到目前为止,我唯一的解决方案是:
So far, the only solution I have is:
> dummyList = list()
> addToList <- function(name, value) {
+ dummyList[[name]] <- value
+ }
> mapply(addToList, c("foo", "bar"), as.list(c(1, 2))
$foo
`1`
$bar
`2`
这似乎是一个相当人为的解决方案,但我不知道如何去做.我遇到的问题是:
This seems like a rather contrived solution, but I can't figure out how to do it otherwise. The problems I have with it are:
它需要创建
dummyList
,即使dummyList
从未改变并且在调用mapply
之后是一个空列表.
It requires the creation of
dummyList
even thoughdummyList
is never changed and is an empty list after the call tomapply
.
如果数字向量 c(1, 2)
未转换为列表,则调用 mapply
的结果是一个命名的双打向量.
If the numeric vector, c(1, 2)
, is not converted to a list, then the result of the call to mapply
is a named vector of doubles.
为了解决问题 2,我总是可以在两个向量上调用 mapply
,然后在结果上调用 as.list
,但似乎应该有一个直接创建一个列表的方法,其中的值在一个向量中.
To get around problem 2, I can always just call mapply
on two vectors and then call as.list
on the result, but it seems like there should be a way to directly create a list with the values being in a vector.
推荐答案
您可以使用 setNames()
setNames(as.list(c(1, 2)), c("foo", "bar"))
(用于列表)或
setNames(c(1, 2), c("foo", "bar"))
(对于向量)
这篇关于从两个向量(名称、值)创建命名列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!