开发者

How to use the value of a variable as key in an R-environment?

开发者 https://www.devze.com 2023-04-05 06:50 出处:网络
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?

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"

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开发者_StackOverflow中文版 is to map the string 'ddd' to the value 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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号