如何在R环境中使用变量的值作为键?

时间:2022-11-09 23:22:56

In R programming language I want to use a hash table.

在R编程语言中,我想使用哈希表。

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"

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.

输出是'key',这意味着我得到了从字符串'key'到值4的映射。我真正想要这个代码做的是将字符串'ddd'映射到值4。

How can I achieve this?

我怎样才能做到这一点?

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.

PS。我没有使用命名列表,因为它使用大量元素很慢,因为它不使用散列来进行搜索。

1 个解决方案

#1


26  

As it says in ?"$":

正如它所说的那样?“$”:

 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

#1


26  

As it says in ?"$":

正如它所说的那样?“$”:

 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