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

发布于 2024-12-04 12:20:13 字数 339 浏览 0 评论 0原文

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

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

例如:

map <- new.env(hash=T, parent=emptyenv())
key <- 'ddd'
map$key <- 4
print(ls(map))
>>[1] "key"

输出是“key”,这意味着我得到了从字符串“key”到值 4 的映射。我真正希望这段代码做的是将字符串“ddd”映射到值 4。

如何才能我实现这个?

附言。我不使用命名列表,因为它对于大量元素来说速度很慢,因为它不使用散列来进行搜索。

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 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冬天旳寂寞 2024-12-11 12:20:13

正如 ?"$" 中所述:

 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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文