Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 428
kevin Avatar asked Apr 26 '18 01:04

kevin


People also ask

Can an R function have no arguments?

Functions are defined using the function() directive and are stored as R objects just like anything else. In particular, they are R objects of class “function”. Here's a simple function that takes no arguments and does nothing.

How do I check if a function is an argument in R?

Get the List of Arguments of a Function in R Programming – args() Function. args() function in R Language is used to get the required arguments by a function. It takes function name as arguments and returns the arguments that are required by that function.

Can functions take another function as an argument in R?

Yes. See the Examples section of ? optim and ? integrate for some R functions that accept other functions as arguments.

Which R prog language function can take an arbitrary number of vectors arguments?

Dots Argument It allows the function to take an arbitrary number of arguments.


1 Answers

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.

like image 155
Hugh Avatar answered Sep 28 '22 09:09

Hugh