Return from indexing function S3 "[" invisible

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

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 
+5
source share
2 answers

The problem is that the value returned from [.mat does not apply to the mat class, since you use unclass , so it uses the default print method for any class that it has. To fix this, just make sure that the returned object is still mat and determines the printing method for mat objects.

 mat <- function(x) { class(x) <- "mat" x } `[.mat` <- function(x, i, j) { y <- mat(unclass(x)[i, j]) invisible(y) } print.mat <- function(x, ...) { invisible(x) } test <- mat(matrix(1:10, ncol = 2)) test[1, 1] # Nothing is printed 
+3
source

You are having problems with the visibility engine 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 primitive, but mean not. From R Internals :

Is the return value of the top-level expression R controlled by the global logical variable R_Visible. This value is set to true (true) or false (false) when entering all primitive and internal functions based on the eval column of the table in the src / main / names.c file: the corresponding parameter can be extracted with the PRIMPRINT macro.

and

Internal and primitive functions force the documented configuration of R_Visible upon return, unless the C code can change it (the exceptions noted above are indicated by PRIMPRINT with a value of 2).

Thus, it seems that you cannot force invisible returns from primitive generics like [ , length , etc., and you should resort to workarounds like the ones Alex suggested.

+6
source

All Articles