首页 > 解决方案 > R Hash - 根据值获取密钥

问题描述

H = hash()
H[["numbers"]] = c(1,2,3)
H[["alpha"]] = c("x","y","z")
H[["animals"]] = c("cat","dog")

现在我想使用“猫”来获取“动物”。根据值获取哈希的键。

标签: rhash

解决方案


我想你正在寻找hash::invert.

invert(H)[["cat"]]
[1] "animals"

这也适用于具有相同值的多个哈希。

H[["mammals"]] = c("cat","dog","human")
invert(H)[["cat"]]
[1] "animals" "mammals"

话虽如此,我同意其他答案,即这是一种执行任务的低效方式。


推荐阅读