R-function values โ€‹โ€‹without a default value that are ignored

We have a function that requires several arguments with no default values โ€‹โ€‹for any of them. However, even if some of them are not specified, the function returns a value if these parameters are used only for a subset of the matrix (and, possibly, other types). We are puzzled why this is so - can anyone help?

In particular, why the following code does not return an error, but sums over the entire matrix and ignores j :

 foo <- function(mat, j){ v <- sum(mat[,j]) v } foo(mat = matrix(1:4,3,4)) 
+5
source share
3 answers

My guess is that an argument is never evaluated.

 foo <- function(x) bar(x) bar <- function(y) missing(y) foo() #[1] TRUE foo(43) #[1] FALSE 

The internal function in your case [ , which has formal arguments i, j, ..., drop = FALSE , most likely checks if argument j absent, and if it is absent, it does not try to evaluate it.

+2
source

According to this blog , optional arguments without defaults are missing from the inside of the function. Testing for it returns TRUE .

 foo <- function(mat, j){ v <- sum(mat[,j]); print(missing(j)) v } foo(mat = matrix(1:4,3,4)) [1] TRUE [1] 30 

Not knowing what the features are, I experimented a bit with sum , and this is what it shows.

 sum(matrix(1:4,3,4)[,NA]) [1] NA sum(matrix(1:4,3,4)[,NULL]) [1] 0 sum(matrix(1:4,3,4)[,]) [1] 30 

If we do not specify any index for the matrix, sum sums all its values.

From reading the blog and a little experiment, I believe that your custom functions work when the functional processes used provide data and can work with missing arguments. In the case of a subset of the matrix, the behavior with missing arguments for the subsets is that the function performs an operation on the entire data set.

+4
source

In addition to @nya answer:

You can avoid this behavior by inserting an if -statement into the function inside the function, which evaluates whether the value j was set when the function was called. If no value is specified, the function throws an error:

 foo <- function(mat, j){ if(missing(j)){ # Check if argument for j has been supplied error("j is not inserted") } else{ v <- sum(mat[,j]) return(v) } } 
0
source

All Articles