[R] Math ops behaviour with multiple classes

Cole Beck cole.beck at vanderbilt.edu
Thu Jun 8 18:40:23 CEST 2017


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



More information about the R-help mailing list