当未提供函数的参数但用于对向量进行子集化时,R不报告错误

kev*_*vin 6 arguments r function parameter-passing

为什么在没有提供b但在函数内部需要时没有报告错误?谢谢!

f2 <- function(a,b) {a[b]}; f2(a=rep(1, 2))
Run Code Online (Sandbox Code Playgroud)

我知道这个函数没有错误:

f <- function(x) {
  10
}
f(stop("This is an error!"))
Run Code Online (Sandbox Code Playgroud)

由于懒惰的评价但是这个

f <- function(x) {
  force(x)
  10
}
f(stop("This is an error!"))
Run Code Online (Sandbox Code Playgroud)

或这个

f <- function(x) {
  x
  10
}
f(stop("This is an error!"))
Run Code Online (Sandbox Code Playgroud)

会产生错误.因为在这两种情况下都在函数中使用 x .以上两个例子都来自http://adv-r.had.co.nz/Functions.html.由于B也使用 F2内,应该有必要增加内部F2力?谢谢!

Hug*_*ugh 6

x[b]x如果b缺少则返回(重复).来自R源:

static SEXP VectorSubset(SEXP x, SEXP s, SEXP call)
{
    R_xlen_t stretch = 1;
    SEXP indx, result, attrib, nattrib;

    if (s == R_MissingArg) return duplicate(x);
Run Code Online (Sandbox Code Playgroud)

https://github.com/wch/r-source/blob/ec2e89f38a208ab02449b706e13f278409eff16c/src/main/subset.c#L169

从文档中,"空"表示"缺失",而不是NULL:

空索引选择所有值:这通常用于替换所有条目但保留属性.