如何在 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?
例如:
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.
我怎样才能做到这一点?
How can I achieve this?
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.
所以你想要:
map[[key]] <- 4
> print(ls(map))
[1] "ddd" "key"
> map[[key]]
[1] 4
这篇关于如何在 R 环境中使用变量的值作为键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文