list 从两个向量(名称、值)创建命名列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17842705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating a named list from two vectors (names, values)
提问by Jon Claus
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.
有没有办法在两个向量上使用 mapply 来构造命名列表?第一个向量将是类型character
并包含用于列表的名称,而第二个包含值。
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:
这似乎是一个相当人为的解决方案,但我不知道如何去做。我遇到的问题是:
It requires the creation of
dummyList
even thoughdummyList
is never changed and is an empty list after the call tomapply
.If the numeric vector,
c(1, 2)
, is not converted to a list, then the result of the call tomapply
is a named vector of doubles.
它需要创建
dummyList
even ifdummyList
永远不会改变并且在调用之后是一个空列表mapply
。如果数字向量
c(1, 2)
未转换为列表,则调用的结果mapply
是双精度命名向量。
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.
为了解决问题 2,我总是可以调用mapply
两个向量,然后调用as.list
结果,但似乎应该有一种方法可以直接创建一个列表,其中的值位于向量中。
回答by Ben Bolker
You can use setNames()
您可以使用 setNames()
setNames(as.list(c(1, 2)), c("foo", "bar"))
(for a list) or
(对于列表)或
setNames(c(1, 2), c("foo", "bar"))
(for a vector)
(对于向量)
回答by joran
I share Ben's puzzlement about why you might want to do this, and his recommendation.
我和 Ben 一样对您为什么要这样做感到困惑,以及他的建议。
Just for curiosity's sake, there is a sort of "hidden" feature in mapply
that will allow this:
出于好奇,有一种“隐藏”功能mapply
可以实现:
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
说:
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.
USE.NAMES 逻辑;如果第一个 ... 参数有名称,则使用名称,或者如果它是字符向量,则使用该字符向量作为名称。
回答by Unai Sanchez
What I propose is made in 2 steps, and it's quite straightforward, so maybe it's easier to understand:
我的建议是分两步完成的,而且很简单,所以也许更容易理解:
test_list <- list(1, 2)
names(test_list) <- c("foo", "bar")
What @ben-bolker proposes works, but just wanted to share an alternative, in case you prefer it.
@ben-bolker 提出的建议有效,但只是想分享一个替代方案,以防万一。
Happy coding!
快乐编码!