[Rd] length(unclass(x)) without unclass(x)?

Henrik Bengtsson henrik.bengtsson at gmail.com
Sun Mar 5 22:56:48 CET 2017


I'm looking for a way to get the length of an object 'x' as given by
base data type without dispatching on class.  Something analogous to
how .subset()/.subset2(), e.g. a .length() function.  I know that I
can do length(unclass(x)), but that will trigger the creation of a new
object unclass(x) which I want to avoid because 'x' might be very
large.

Here's a dummy example illustrating what I'm trying to get to:

> x <- structure(double(1e6), class = c("foo", "numeric"))
> length.foo <- function(x) 1L
> length(x)
[1] 1
> length(unclass(x))
[1] 1000000

but the latter call will cause an internal memory allocation:

> profmem::profmem(length(unclass(x)))
Rprofmem memory profiling of:
length(unclass(x))

Memory allocations:
        bytes      calls
1     8000040 <internal>
total 8000040

In my use case, I have control over neither the class of 'x' (it can
be any class from any package) nor the implementation of length() for
the class.  I'm not sure, but in the "old old days", I think I could
have called base::length.default(x) to achieve this.  Does anyone know
of a way to infer length(unclass(x)) without going via unclass(x)?  I
prefer to do this with the existing R API and not having to implement
it in native code.

Thanks,

Henrik



More information about the R-devel mailing list