Toño Toño - 3 months ago 46
R Question

Return invisible and visible output in R

I would like to return a mix of visible and invisible objects with a function. I tried with a list that looks like:

return(list(inv=invisible(x), vis=y))
or
return(list(invisible(inv=x), vis=y))
but it didn't work.

I appreciate any ideas. Thanks in advance!

Answer

I think the easiest solution is just to create an S3 print method and add a class tag to the list

create_list = function(a, b) {
  l = list(a=a, b=b)
  class(l) = "mylist"
  l
}

Then create a corresponding print method that only prints out the second element:

print.mylist = function(x, ...){
  x = x["b"]
  NextMethod()
}

and that's it:

R> (l = create_list(1:4, 5:10))
$b
[1]  5  6  7  8  9 10

R> str(l)
List of 2
 $ a: int [1:4] 1 2 3 4
 $ b: int [1:6] 5 6 7 8 9 10
 - attr(*, "class")= chr "mylist"