[R] Math ops behaviour with multiple classes

Bert Gunter bgunter.4567 at gmail.com
Thu Jun 8 23:45:36 CEST 2017


I think you may be confusing (S3) class and ?mode.

> x <- seq.int(1:3)
> class(x)
[1] "integer"
> mode(x)
[1] "numeric"
> class(x+.5) ## coercion
[1] "numeric"
> mode(x+.5)
[1] "numeric"

But note:

> y <- as.integer(1)
> class(y)
[1] "integer"
> class(y) <- "foo"
> mode(y)
[1] "numeric"
> class(y+.5)
[1] "foo"
> mode(y+.5)
[1] "numeric"

And further:

> class(y) <-c("foo","integer")
> class(y+.5)
[1] "foo"     "integer"

So basically, the behavior seems to be: when the class attribute can
be coerced to "numeric" by as.numeric(), it is. Otherwise it is left
as is.

Note that log is a primitive function not in the Ops groups, but has
similar behavior.

I would guess (corroboration or correction by more knowledgeable folks
appreciated!) that this sort of semi-confusion with S3 classes was one
of the motivators for adding the more rigorous S4 system.

HTH

Cheers,
Bert


Bert Gunter

"The trouble with having an open mind is that people keep coming along
and sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )


On Thu, Jun 8, 2017 at 9:40 AM, Cole Beck <cole.beck at vanderbilt.edu> wrote:
> I would expect that several math operations should always return values with
> a class of numeric.  If the input is defined with multiple classes, however,
> the class attribute is preserved.  I would think this may have some
> unintended side-effects.  Here's an example:
>
>> sessionInfo()$R.version$version.string
> [1] "R version 3.4.0 (2017-04-21)"
>> x <- seq.int(5)
>> class(x)
> [1] "integer"
>> class(log(x))
> [1] "numeric"
>> class(x) <- c("integer", "foo")
>> log(x)
> [1] 0.0000000 0.6931472 1.0986123 1.3862944 1.6094379
> attr(,"class")
> [1] "integer" "foo"
>> x + 0.5
> [1] 1.5 2.5 3.5 4.5 5.5
> attr(,"class")
> [1] "integer" "foo"
>
> I do see the note in ?Arithmetic that states "All attributes (including
> class) are preserved if there is no coercion".  Is this correct, or should
> the returned value have an updated class of c("numeric", "foo")? Should foo
> have its own methods to coerce the output to numeric?
>
> Thanks,
> Cole
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list