I am currently developing a package in R with the "help" of devtools. That is, the package is getting loaded into R studio via load_all(path = ...)
in this stage and my functions from the R directory are made available. So far so good.
But when I try to implement a simple S3 hierarchy within my package, the dispatching will not work - it throws the following error:
Error in UseMethod("generic_function", obj) : no applicable method for 'generic_function' applied to an object of class "c('data.frame', 'myclass')"
However, when I implement the same generic function as well as its methods and load them in the current environment explicitly the dispatching will work.
I cannot explain what is going on under the hood here. The dispatching will simply not work when I load the package but it works when "loading it on the fly" in the environment.
I appreciate your help. BR
... as requested the code:
scaler <- function (solvertraj, ...) {
UseMethod("scaler", solvertraj)
}
scaler.scale_multi <- function(solvertraj, ...){
resls = list()
ls = c("incumbant", "average.fitness")
min_inc = min(solvertraj$incumbant)
max_inc = max(solvertraj$incumbant)
for(i in 1:length(ls)){
tobe_scaled = ls[i]
tmp = sapply(solvertraj[tobe_scaled], function(x){
(x-min_inc) / (max_inc -min_inc)
})
resls[[i]] = tmp
}
#attr(solvertraj,'MIN_MAX_scaled') <<- TRUE
return(resls)
}
scaler.scale_other <- function(solvertraj, ...){
res = list()
plls = list()
shapirols = list()
resls = list()
ls = c("incumbant", "average.fitness")
for(i in 1:length(ls)){
col = ls[i]
# 1) shrink range
tmp = sapply(solvertraj[col], function(x){
x - min(solvertraj["incumbant"])
})
# 2) use natural logarithm
tmp_2 = sapply(tmp, log)
tmp_2[length(tmp_2)] <- 0L
res[[i]] = tmp_2
# TODO: fix
plot_trans = plot(density(tmp_2))
plls[[i]] = plot_trans
tmp_test = shapiro.test(tmp_2)
shapirols[[i]] <- tmp_test
}
resls = list.append(resls,
scales = res,
plots = plls,
shapirols = shapirols)
#attr(solvertraj,'SHRINKAGE_scaled') <<- TRUE
return(resls)
}
The post is old, but this is an answer for people who'd face the same issue. I think the explanation might be you weren't using a proper workflow while using devtools
:
print.myclass <- function(x, ...){}
document()
before load_all()
(this is how NAMESPACE will get properly updated)load_all()
If you skip document()
and only run load_all()
, you'll load your print.myclass
, you'll be able to call it directly with print.myclass(instance_myclass)
and get the intended result. sloop::s3_dispatch(print(instance_myclass))
will confusingly tell you that it understands it should dispatch print
to your method... but you'll get default print
when calling print(instance_myclass)
...
#' @export
was probably not the problem here, even though S3 methods should be exported. It was probably due to incorrect NAMESPACE in your dev environment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With