Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make return from S3 indexing function "[" invisible

Tags:

r

Is it possible to return an invisible object when using the S3 indexing function "[" on a custom class? For example, in the code below, is there a way to make the last line of code not print anything?

mat <- function(x) {
  structure(x, class="mat")
}

"[.mat" <- function(x, i, j) {
  invisible(unclass(x)[i,j])
}

m1 <- mat(matrix(1:10, ncol=2))
m1[1:2,]

     [,1] [,2]
[1,]    1    6
[2,]    2    7
like image 241
Abiel Avatar asked May 14 '15 20:05

Abiel


1 Answers

You are running into issues with the visibility mechanism caused by primitive functions. Consider:

> length.x <- function(x) invisible(23)
> length(structure(1:10, class="x"))
[1] 23
> mean.x <- function(x) invisible(23)
> mean(structure(1:10, class="x"))
> # no output

length is a primitive, but mean is not. From R Internals:

Whether the returned value of a top-level R expression is printed is controlled by the global boolean variable R_Visible. This is set (to true or false) on entry to all primitive and internal functions based on the eval column of the table in file src/main/names.c: the appropriate setting can be extracted by the macro PRIMPRINT.

and

Internal and primitive functions force the documented setting of R_Visible on return, unless the C code is allowed to change it (the exceptions above are indicated by PRIMPRINT having value 2).

So it would seem that you cannot force invisible returns from primitive generics like [, length, etc., and you must resort to workarounds like the one suggested by Alex.

like image 82
BrodieG Avatar answered Oct 27 '22 18:10

BrodieG