2021年4月9日星期五

R: How to truly remove an S4 slot from an S4 object

Let's say I define an S4 class 'foo' with two slots 'a' and 'b', and define an object x of class 'foo',

setClass(Class = 'foo', slots = c(    a = 'numeric',    b = 'character'  ))  x <- new('foo', a = rnorm(1e3L), b = rep('A', times = 1e3L))  format(object.size(x), units = 'auto') # "16.5 Kb"  

Then I want to remove slot 'a' from the definition of 'foo'

setClass(Class = 'foo', slots = c(    b = 'character'  ))  slotNames(x) # slot 'a' automatically removed!! wow!!!  

I see that R automatically take cares my object x and have the slot 'a' removed. Nice! But wait, the size of object x is not reduced.

format(object.size(x), units = 'auto') # still "16.5 Kb"  format(object.size(new(Class = 'foo', x)), units = 'auto') # still "16.5 Kb"  

Right.. Somehow 'a' is still there but I just cannot do anything to it

head(x@a) # `'a'` is still there  rm(x@a) # error  x@a <- NULL # error  

So question: how can I really remove slot 'a' from x and have its size reduced (which is my primary concern)?

https://stackoverflow.com/questions/67028788/r-how-to-truly-remove-an-s4-slot-from-an-s4-object April 10, 2021 at 05:58AM

没有评论:

发表评论