R Package development: redefining a function from one package with a function from another?

I am currently developing two packages, the following is a simplified version of my problem:

In package A, I have some functions (say sum_twice), and I call another function inside the package (say "slow_sum"). However, in package B, I wrote another function (say, "fast_sum"), with which I want to replace the slow function in package A.

Now, how do I manage this "override" of the "slow_sum" function using the fast_sum function?

Here is a simplified example of such functions (just for illustration):

############################

##############
# Functions in package A

slow_sum <- function(x) {
sum_x <- 0
for(i in seq_along(x)) sum_x <- sum_x + x[i]
 sum_x
}

sum_twice <- function(x) {
x2 <- rep(x,2)
slow_sum(x2)
}

##############
# A function in package B
fast_sum <- function(x) { sum(x) }

############################

If I do something like slow_sum <- fast_sumthis, this will not work, since sum_twice uses the slow_sum from the NAMESPACE package A.

"B":

assignInNamespace(x = "slow_sum", value = B:::fast_sum, ns = "A")

, , CRAN ":", assignInNamespace ( , ).

. "sum_twice" "fast_sum" "Slow_sum"?

, , Tal

p.s: .

UDPATE:

, R ( ), dendextend ( CRAN). Rcpp ( dendextendRcpp, github). , , . , , assignInNamespace, CRAN + , CRAN ( ).

, , . , , - ( , , ). - dendextend dendextendRcpp , , . , ( , - , ). ? .

+3
2

, ( Uwe Kurt), "local" . , "dendextend_options" : https://github.com/talgalili/dendextend/blob/master/R/zzz.r

:

dendextend_options <- local({
   options <- list()
   function(option, value) {
      #          ellipsis <- list(...)         
      if(missing(option)) return(options)

      if(missing(value))
         options[[option]]
      else options[[option]] <<- value
   }
})
 dendextend_options("a")
 dendextend_options("a", 1)
 dendextend_options("a")
 dendextend_options("a", NULL)
 dendextend_options("a")
 dendextend_options()
+1

sum_twice:

my_sum_ch <- getOption("my_sum", if ("package:fastpkg" %in% search()) 
                       "fast_sum" else "slow_sum")
my_sum <- match.fun(my_sum_ch)

​​ "my_sum", my_sum, , fastpkg.

+2

All Articles