r - Make return from S3 indexing function "[" invisible -
is possible return invisible object when using s3 indexing function "[" on custom class? example, in code below, there way make 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
the problem value returned [.mat
not of class mat
since you're using unclass
, uses default printing method whatever class has. fix this, ensure returned object still mat
, define printing method 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 printed
Comments
Post a Comment