如何在R环境中使用变量的值作为键? [英] How to use the value of a variable as key in an R-environment?
本文介绍了如何在R环境中使用变量的值作为键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在R编程语言中,我想使用一个散列表。
In R programming language I want to use a hash table.
如何使用变量的值作为环境的关键字?
How do I use the value of a variable as the key for the environment?
例如:
For example:
map <- new.env(hash=T, parent=emptyenv())
key <- 'ddd'
map$key <- 4
print(ls(map))
>>[1] "key"
输出是'key',这意味着我从字符串'key '到值4.我真的想要这段代码做的是将字符串'ddd'映射到值4.
The output is 'key', which means I get a mapping from the string 'key' to the value 4. What I really want this code to do is to map the string 'ddd' to the value 4.
我怎么能做到这一点?
PS。我不使用命名列表,因为它使用大量元素的速度很慢,因为它不使用哈希来执行搜索。
PS. I don't use named list because it's slow with large amount of elements as it does not use hashing to do the search.
推荐答案
正如它在?$
中所说:
Both ‘[[’ and ‘$’ select a single element of the list. The main
difference is that ‘$’ does not allow computed indices, whereas
‘[[’ does. ‘x$name’ is equivalent to ‘x[["name", exact =
FALSE]]’. Also, the partial matching behavior of ‘[[’ can be
controlled using the ‘exact’ argument.
所以你想要:
So you want:
map[[key]] <- 4
> print(ls(map))
[1] "ddd" "key"
> map[[key]]
[1] 4
这篇关于如何在R环境中使用变量的值作为键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文