0

I believe a similar question has been asked here. However, I am still having trouble adding my own function to an existing package. I've tried

myfun <- function(x) print(x)
environment(myfun) <- asNamespace('stats')

However, when I call

stats::myfun

It tells me that Error: 'myfun' is not an exported object from 'namespace:stats'. How can I export myfun?

Community
  • 1
  • 1
Adrian
  • 9,229
  • 24
  • 74
  • 132
  • Did you try this too? `environment(myfun) <- as.environment("package:stats")` – NelsonGon Feb 29 '20 at 05:37
  • Just tried that. Running `stats::myfun` still gives me the same error. – Adrian Feb 29 '20 at 05:40
  • What exactly is your goal here? Since you defined the function in the GlobalEnvironment, I don't see for calling it using the `::`- Notation. Even if that should work, it is not the case that `myfun()` would still be a part of `stats` after you reload the package. For this, you would need to download the source code of the package, add the function there and then install your version of `stats`. – Stibu Feb 29 '20 at 13:43
  • If this is about accessing hidden objects from `stats`, the method seems to work. Try this function: `myfun <- function() print(.approxfun)` and run it before and after changing its environment with `environment(myfun) <- asNamespace("stats")`.But in this case, I think it would be easier to just use `stats:::.approxfun`. – Stibu Feb 29 '20 at 13:43
  • Thanks for your response. I wanted to add my own function to a package because when I run `foreach`, for some reason my own function `myfun` is always not found (even though I've already defined it in the GlobalEnvironment). Therefore, I wanted to add `myfun` to an existing package so that when I call `foreach(..., .export = "stats") that `myfun` will be used when I specify `stats::myfun(...)`. – Adrian Feb 29 '20 at 15:09
  • It seems, then, that your question is not about your actual problem, but rather about a specific approach to solve that problem. I strongly doubt that this is the right approach though, as this would make `foreach()` terribly complicated to use. I suggest that you ask about your real problem instead, either by editing this question or by starting a new questions. (Since this question has no answers, you could deleted it after you started the new question.) – Stibu Mar 01 '20 at 07:01
  • Please add a [minimal reproducible example](https://stackoverflow.com/q/5963269/4303162) where you define a simple function and run `foreach()` in such a way that you get the same error message as in your original code. If you need a data set to work with, you could use one of the R built-in datasets like `mtcars`. – Stibu Mar 01 '20 at 07:02

0 Answers0