Question

Is it possible to have slots in a S4 class to be lists of another custom type? like

setClass("customClass", 
          representation(list(anotherCustomClass)
)
Was it helpful?

Solution

For those looking for an answer to this. No, there is no way to restrict a list in S4 to have elements of certain type. This actually makes sense, since lists in R are designed to contain any type of element, so why lists on S4 should be distinct?

OTHER TIPS

Here is a fairly simple implementation of a typed list using S4. Checks that all objects are of the specified type and that all of these objects are validObjects of that type.

instanceof = function(object, type) {
  class(object)[[1]] == type
}

typed_list_check = function(object) {

  errors = character()
  is_correct_object_type = logical()

  if (length(object@objects) >= 1) {
    for (i in 1:length(object@objects)) {
      obj = object@objects[[i]]
      is_correct_object_type[[i]] = instanceof(obj, object@type)
    }

    if (any(!is_correct_object_type)) {
      msg = sprintf("At least one object is not of type %s.", object@type)
      errors = c(errors, msg)
    }

    if (all(is_correct_object_type)) {
      for (obj in object@objects) {
        potential_msg = validObject(obj)
        if (is.character(potential_msg)) {
          msg = potential_msg
          errors = c(errors, msg)
        }
      }
    }
  }

  if (length(errors) == 0) TRUE else errors
}

setClass(
  "TypedList",
  representation(
    type = "character",
    objects = "list"
  ),
  validity = typed_list_check
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top