Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP函数isset的R版本_R - Fatal编程技术网

PHP函数isset的R版本

PHP函数isset的R版本,r,R,我经常发现PHP中的isset()非常有用。尝试创建it的R版本时,我想到了以下几点: isset <- function(x){ a <- try(x, silent = TRUE) return(!inherits(a, "try-error") && !is.null(a) && (length(a) != 1L || !is.na(a))) } 2) 更有用,但使用is.null()仍然可行 几乎所有的时间都花在了try上 Q:考

我经常发现
PHP
中的
isset()
非常有用。尝试创建it的
R
版本时,我想到了以下几点:

isset <- function(x){

  a <- try(x, silent = TRUE)
  return(!inherits(a, "try-error") && !is.null(a) && (length(a) != 1L || !is.na(a)))

}
2) 更有用,但使用is.null()仍然可行

几乎所有的时间都花在了
try


Q:考虑到在上述三种情况下都需要返回
FALSE
,您如何重新写入
isset
,使其至少快两倍?

使用内置的
exists

isset <- function(x) {
  is_variable <- make.names(name <- deparse(substitute(x))) == name
  if (is_variable && !exists(name)) return(FALSE)
  !is.null(x) && (length(x) != 1L || !is.na(x))
}

# > microbenchmark(isset(test_var), isset(test_var$b))
# Unit: microseconds
#              expr    min      lq median      uq     max neval
# isset(test_var)   28.011 28.9115 29.278 29.6445  41.960   100
# isset(test_var$b) 47.656 49.1515 49.690 50.4170 137.049   100

以这种方式设置,它无法检测
a$b
是否存在。where
一个更好更快的感谢。但是,如果您想检查
test\u var$b
并且
test\u var
不存在,它将失败。这些类型的值有一个无休止的排列,只有
tryCatch
才能完全捕获,这很可能是图灵完全问题。(例如,
some_函数(a$b[[some_-other_函数('some_值')]]]$etc)
)。如果您仅限于一类表达式,如
a$b$c
等,您可以先通过
gsub('\\$.'','',name)
获得更好的结果。
> test_var <- list(a = 1)
> microbenchmark(isset(test_var$b))
Unit: microseconds
              expr    min    lq median     uq     max neval
 isset(test_var$b) 12.509 13.15 13.791 14.112 112.892   100
> rm(test_var)
> microbenchmark(isset(test_var), isset(test_var$b), try(test_var$b, silent = TRUE))
Unit: microseconds
                           expr     min       lq   median       uq      max neval
                isset(test_var) 736.038 764.1015 780.4575 815.5755 1223.844   100
              isset(test_var$b) 737.001 764.7425 786.0700 815.0940  986.837   100
 try(test_var$b, silent = TRUE) 732.832 760.2525 779.3345 815.4155 1034.944   100
isset <- function(x) {
  is_variable <- make.names(name <- deparse(substitute(x))) == name
  if (is_variable && !exists(name)) return(FALSE)
  !is.null(x) && (length(x) != 1L || !is.na(x))
}

# > microbenchmark(isset(test_var), isset(test_var$b))
# Unit: microseconds
#              expr    min      lq median      uq     max neval
# isset(test_var)   28.011 28.9115 29.278 29.6445  41.960   100
# isset(test_var$b) 47.656 49.1515 49.690 50.4170 137.049   100