在R编程语言中,我想使用哈希表。
如何使用变量的值作为环境的键?
例如:
map <- new.env(hash=T, parent=emptyenv())
key <- 'ddd'
map$key <- 4
print(ls(map))
>>[1] "key"
输出为“key”,这意味着我得到了从字符串“key”到值4的映射。我真正希望此代码执行的操作是将字符串“ddd”映射到值4。
我该如何实现?
PS。我不使用命名列表,因为它使用大量元素的速度很慢,因为它不使用哈希进行搜索。
最佳答案
就像?"$"
中所说的:
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 - 如何在R环境中将变量的值用作键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7432248/