从两个向量(名称、值)创建命名列表 [英] Creating a named list from two vectors (names, values)

查看:27
本文介绍了从两个向量(名称、值)创建命名列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在两个向量上使用 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:

  1. 它需要创建 dummyList,即使 dummyList 从未改变并且在调用 mapply 之后是一个空列表.

  1. It requires the creation of dummyList even though dummyList is never changed and is an empty list after the call to mapply.

如果数字向量 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆