如何将变量键/值对添加到列表对象? [英] How to add variable key/value pair to list object?
本文介绍了如何将变量键/值对添加到列表对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个变量key
和value
,我想将它们作为键/值对添加到列表中:
I have two variables, key
and value
, and I want to add them as a key/value pair to a list:
key = "width"
value = 32
mylist = list()
mylist$key = value
结果是这样的:
mylist
# $key
# [1] 32
但是我要这样:
mylist
# $width
# [1] 32
我该怎么做?
推荐答案
R列表可以看作是可以通过名称访问的对象的哈希向量.使用这种方法,您可以像这样将新条目添加到列表中:
R lists can be thought of as hashes- vectors of objects that can be accessed by name. Using this approach you can add a new entry to the list like so:
key <- "width"
value <- 32
mylist <- list()
mylist[[ key ]] <- value
在这里,我们使用存储在变量键中的字符串来访问列表中的位置,就像使用存储在循环变量i中的值来通过以下方式访问向量一样:
Here we use the string stored in the variable key to access a position in the list much like using the value stored in a loop variable i to access a vector through:
vector[ i ]
结果是:
myList
$width
[1] 32
这篇关于如何将变量键/值对添加到列表对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文