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

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

问题描述

有没有办法使用mapply在两个向量构造一个命名列表?第一个向量的类型为字符,包含用于列表的名称,第二个包含值。

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 永远不会改变,并且是在调用 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天全站免登陆