用于向量查找的R惯用语 [英] R idiom for vector lookup

查看:80
本文介绍了用于向量查找的R惯用语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我写的一个函数:

lookup <- function (keys, values, key, default) {
  found <- which(keys == key)
  if (length(found) == 1) return(values[found])
  if (length(found) == 0) return(default)
  stop("lookup(",keys,",",values,",",key,",",default,"): duplicate keys")
}

它可以满足我的需要:

> lookup(c("a"),c(3),"a",0)
[1] 3
> lookup(c("a"),c(3),"b",0)
[1] 0
> lookup(c("a","a"),c(3),"a",0)
Error in lookup(c("a", "a"), c(3), "a", 0) : lookup(aa,3,a,0): duplicate keys

问题是:在造型上看起来正确吗? 我错过了什么吗?

the question is: does it look stylistically right? am I missing something?

(特别是,我希望此函数被编写为单个表达式).

(specifically, I expect this function to be written as a single expression).

我确实知道这涉及到完整的向量查找,因此效率低下,如果我想快速执行此操作,则应该使用data.table.幸运的是,这种情况下的性能并不重要,因为我的数据非常小.

I do understand that this involves full vector lookup and, as such, is inefficient, and I should be using data.table if I want this to be fast. Fortunately, the performance in this case is not important as my data is very very small.

谢谢!

推荐答案

R通过names

dict <- c("Key1"="val1", "Key2"="val2")

dict[["Key1"]]
# [1] "val1"


dict[["Key3"]]
# Error in dict[["Key3"]] : subscript out of bounds


如果您需要提供默认值的函数:

getVal <- function(key, dict=defaultDict) { 
  if (! key %in% names(dict) )
    return(defaultValue)

  dict[[key]]
}

这篇关于用于向量查找的R惯用语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆