i have defined a method for printing a vector with the class test:
print.test <- function(x, ...) {
x <- formatC(
as.numeric(x),
format = "f",
big.mark = ".",
decimal.mark = ",",
digits = 1
)
x[x == "NA"] <- "-"
x[x == "NaN"] <- "-"
print.default(x)
}
which works fine for the following
a <- c(1000.11, 2000.22, 3000.33)
class(a) <- c("test", class(a))
print(a)
[1] "1.000,11" "2.000,22" "3.000,33"
this also works:
round(a)
[1] "1.000,0" "2.000,0" "3.000,0"
this does not:
median(a)
[1] 2000.22
class(median(a))
[1] "numeric"
now my question is: do i need to write a custom method for this class to use median e.g. and if so what would it look like or is there another way (as i simply would like this class to print the data in a certain format)?
The problem is that
median.default
returns an object of classnumeric
therefore autoprinting of the returned object does not call your customprint
method.The following will do so.
As for the handling of
NA
values, I will first define another method for a base R function. It is not strictly needed but save some code lines if objects of classtest
are used frequently.EDIT.
The following defines a generic function
wMedian
, a default method and a method for objects of class"currency"
, as requested by the OP in a comment.Note that there must be a method
print.currency
, which I don't redefine since it's exactly the same asprint.test
above. As for the other methods, I have made them simpler with the help of a new function,as.currency
.