SamPassmore
SamPassmore

Reputation: 1365

Hidden objects in list

I am creating a custom object for a package and I want to have a list of two objects, but for one of those elements to be 'hidden'

For example:

l = list(data = data.frame(a = 1:3, b = 4:6), hidden = list(obj1 = 1, obj2 = 2)) 

When I interact with the list I want to only interact with the data element and the other be only accessed specifically.

So, if i typed l

> l
  a b
1 1 4
2 2 5
3 3 6

Which I can manage with a custom print method. But I also want to be able to do

> l[,1]
[1] 1 2 3

Which I don't think is possible with a custom print method.

I don't have any specific requirements for how the other element should be accessed, but something 'R friendly' I guess.

Is there a different class I should be using or creating a new class? Any advice would be appreciated.

Upvotes: 2

Views: 807

Answers (2)

moodymudskipper
moodymudskipper

Reputation: 47350

I think it would be cleaner for you to use attributes :

l <- list(data = data.frame(a = 1:3, b = 4:6),
          hidden = list(obj1 = 1, obj2 = 2))

foo <- function(x){
  attr(x$data,"hidden") <- x$hidden
  x$data
}

l <- foo(l) 
l
#   a b
# 1 1 4
# 2 2 5
# 3 3 6

l[,1]
# [1] 1 2 3

attr(l,"hidden")
# 
# [1] 1
# 
# 
# [1] 2
# 

Upvotes: 1

Julius Vainora
Julius Vainora

Reputation: 48251

You could indeed define a custom class for your object. Let

class(l) <- "myclass"

Then you may define custom-specific methods for your functions of interest. For instance, in the case of l[, 1] we have

`[.myclass` <- function(x, ...) `[`(x[[1]], ...)

which takes this double list and then calls the usual [ function on the first list element:

l[, 1]
# [1] 1 2 3

The same can be done with other functions, such as print:

fun.myclass <- function(x, ...) fun(x[[1]], ...)

And you still can always access the second object in the usual way,

l$hidden
# $obj1
# [1] 1
#
# $obj2
# [1] 2

Upvotes: 4

Related Questions