R does not report error when an argument of a function is not provided but used for subsetting a vector

  • A+
Category:Languages

Why there is no error reported when b is not supplied but required inside the function? Thanks!

f2 <- function(a,b) {a[b]}; f2(a=rep(1, 2)) 

I understand that there is no error in this function:

f <- function(x) {   10 } f(stop("This is an error!")) 

due to lazy evaluation But this

f <- function(x) {   force(x)   10 } f(stop("This is an error!")) 

or this

f <- function(x) {   x   10 } f(stop("This is an error!")) 

will produce an error. Because in both cases x is used within the function. Both the above two examples are from http://adv-r.had.co.nz/Functions.html. Since b is also used within f2, should it be necessary to add force inside f2? Thanks!


x[b] returns (a duplicate of) x if b is missing. From the R source:

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); 

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

From the documentation, in which 'empty' means 'missing', not NULL:

An empty index selects all values: this is most often used to replace all the entries but keep the attributes.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: