2

我的预感是这是对R语言的滥用,并且有充分的理由不会发生这种情况。但我发现这是我试图调试的代码中潜在错误的永久来源:

MWE

list.1 <- list(a=1,b=2,c=list(d=3))
list.2 <- list(b=4,c=list(d=6,e=7))
input.values <- list(list.1,list.2)
do.something.to.a.list <- function(a.list) {
    a.list$b <- a.list$c$d + a.list$a
    a.list
}
experiment.results <- lapply(input.values,do.something.to.a.list)

use.results.in.some.other.mission.critical.way <- function(result) {
    result <- result^2
    patient.would.survive.operation <- mean(c(-5,result)) >= -5
    if(patient.would.survive.operation) {
        print("Congrats, the patient would survive! Good job developing a safe procedure.")
    } else {
        print("Sorry, the patient won't make it.")
    }
}

lapply(experiment.results, function(x) 

use.results.in.some.other.mission.critical.way(x$b))

的,我知道这是一个愚蠢的例子,我可以在尝试访问它之前添加一个元素是否存在的检查。但我并不是要知道我能做什么,如果我一直都有完美的记忆和意识,慢慢地解决这个功能不方便并让我很头疼的事实。我试图完全避免头痛,也许是以代码速度为代价。

所以:我想知道的是...

(a) 是否有可能做到这一点。我最初的尝试失败了,我被困在试图阅读C“$”的内部以了解如何正确处理参数

(b) 如果是这样,是否有充分的理由不(或不)这样做。

基本上,我的想法是,与其编写每个依赖于从列表访问中返回的非 null 的函数来仔细检查,我可以只编写一个函数来仔细检查并相信其余函数不会被调用未满足的先决条件 b/c 失败的列表访问将快速失败。

4

1 回答 1

2

您可以覆盖 R 中的几乎任何东西(据我所知,某些特殊值除外 - NULL, NA, NA_integer_ NA_real_ NA_complex_, NA_character_, NaN, Inf, )。TRUEFALSE

对于您的具体情况,您可以这样做:

`$` <- function(x, i) {
  if (is.list(x)) {
    i_ <- deparse(substitute(i))
    x_ <- deparse(substitute(x))
    if (i_ %in% names(x)) {
      eval(substitute(base::`$`(x, i)), envir = parent.frame())
    } else {
      stop(sprintf("\"%s\" not found in `%s`", i_, x_))
    }
  } else {
    eval(substitute(base::`$`(x, i)), envir = parent.frame())
  }
}

`[[` <- function(x, i) {
  if (is.list(x) && is.character(i)) {
    x_ <- deparse(substitute(x))
    if (i %in% names(x)) {
      base::`[[`(x, i)
    } else {
      stop(sprintf("\"%s\" not found in `%s`", i, x_))
    }
  } else {
    base::`[[`(x, i)
  }
}

例子:

x <- list(a = 1, b = 2)
x$a
#[1] 1
x$c
#Error in x$c : "c" not found in `x`
col1 <- "b"
col2 <- "d"
x[[col1]]
#[1] 2
x[[col2]]
#Error in x[[col2]] : "d" not found in `x`

它会大大降低您的代码速度:

microbenchmark::microbenchmark(x$a, base::`$`(x, a), times = 1e4)
#Unit: microseconds
#            expr    min     lq     mean median      uq      max neval
#             x$a 77.152 81.398 90.25542 82.814 85.2915 7161.956 10000
# base::`$`(x, a)  9.910 11.326 12.89522 12.033 12.3880 4042.646 10000

我已将其限制为lists(其中将包括data.frames)并[[通过数字和字符向量实现了选择,但这可能不能完全代表可以使用$和使用的方式。[[

请注意,[[您可以使用@rawr 的更简单的代码:

`[[` <- function(x, i) if (is.null(res <- base::`[[`(x, i))) simpleError('NULL') else res

但这将为列表中的成员抛出错误,NULL而不仅仅是未定义。例如

x <- list(a = NULL, b = 2)
x[["a"]]

这当然可能是所希望的。

于 2015-08-03T13:28:23.827 回答