Best practice for preserving class

For functions which do not preserve the class of the input object, I make wrappers that generally look like this:

fn_wrap <- function (x) {
  old_class <- class(x)
  x <- fn(x)  # which does not preserve x's class...
  class(x) <- unique(class(x), old_class)

Am I wrong? Is this right?

Probably not safe. The class name is often certifying that certain other things are true about the object (which may have also been lost).

Also you might want to double check the following behavior of unique() (it expects all of its values in a single vector, not as separate arguments).

unique("a", "b")
# [1] "a"
unique(c("a", "b"))
# [1] "a" "b"

Yes, I need a c() in unique().

But you are right about certification of an object. More broadly, this is the same work flow I use to preserve attributes in general -- assign the pre-modified object's attributes to a variable (at least the ones I want to preserve) and then re-assign them after some non-attribute preserving function has been ran.

This is what I do to get by, but I am always open to better, safer ways of doing things.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.