I need to modify the function gamGPDfit() in the package QRM to solve a problem. The function gamGPDfit() in turn calls other functions fit.GPD() and gamGPDfitUp() to compute the estimates of the parameters.
The structure of the function is shown below:
#######################################################
gamGPDfit<-function (..., init = fit.GPD(...) , ...)
{
...
Par<-gamGPDfitUp(...)
...
return (list(...))
}
<environment: namespace:QRM>
#######################################################
Now, when I call fit.GPD(), I get the function on the command window to make the necessary modifications. However, the other function gamGPDfitUp() returns
> gamGPDfitUp
Error: object 'gamGPDfitUp' not found
The question is, how do I get such an in-built function within another function? Does it have to do with the environment QRM? If so how do I obtain the function to modify it?.
I have attached the function and the call of the gamGPDfitUp() is indicated in colour red.
There's a couple of things that may come in handy.
One is help(":::") - Accessing exported and internal variables in a namespace. You can access GamGPDfitUp probably by prefixing it with QRM:::.
Another function is fixInNamespace, which allows you to modify functions inside packages. The help page for this one lists a few more interesting tools. Play around with this and it should solve most of your problems.
Related
I use the following code in my own package.
graphics::curve( foo (x) )
When I run R CMD check, it said the following note.How do I delete the NOTE?
> checking R code for possible problems ... NOTE
foo: no visible binding for global variable 'x'
Undefined global functions or variables:
x
Edit for the answers:
I try the answer as follows.
function(...){
utils::globalVariables("x")
graphics::curve( sin(x) )
}
But it did not work. So,..., now, I use the following code, instead
function(...){
x <-1 # This is not used but to avoid the NOTE, I use an object "x".
graphics::curve( sin(x) )
}
The last code can remove the NOTE.
Huuum, I guess, the answer is correct, but, I am not sure but it dose not work for me.
Two things:
Add
utils::globalVariables("x")
This can be added in a file of its own (e.g., globals.R), or (my technique) within the file that contains that code.
It is not an error to include the same named variables in multiple files, so the same-file technique will preclude you from accidentally removing it when you remove one (but not another) reference. From the help docs: "Repeated calls in the same package accumulate the names of the global variables".
This must go outside of any function declarations, on its own (top-level). While it is included in the package source (it needs to be, in order to have an effect on the CHECK process), but otherwise has no impact on the package.
Add
importFrom(utils,globalVariables)
to your package NAMESPACE file, since you are now using that function (unless you want another CHECK warning about objects not found in the global environment :-).
I am building a package with functions that have default arguments. I would like to find a clean way to set the values of the default arguments once the function has been imported.
My first attempt was to set the default values to unknown objects (within the package). Then when I load the package, I would have a external script that would assign a value to the unknown objects.
But it does not seem very clean since I am compiling a function with an unknown object.
My issue is that I will need other people to use the functions, and since they have many arguments I want to keep the code as concise as possible. And many arguments can be set by a configuration script before running the program.
So, for instance, I define in my package:
function_try <- function(x = VAL){
return(x)
}
I compile the package and load it, and then I have an external script that does (or reading from a config file)
VAL <- "hello"
And then a user of the function can just run
function_try()
I would use options for that. So your function looks like:
function_try <- function(x = getOption("mypackage.default.value")) x
In your external script you make sure that the option value is set:
options(mypackage.default.value = "hello")
IMHO that is a clean solution, because anybody reading your function will see at first sight that a certain options value is used as a default and has also a clear understanding of how to overwrite this value if needed.
I would also define a fall back value in your library onLoad to make sure that the value is defined in the first place. You can then even react in your functions to this fallback value and issue a meaningful warning if the function realizes that the the external script did for whatever reason not provide a new value.
I would like to have a simple function to clear my workspace in R, but I seem to be having issues. I have my code below.
clear() = function() rm(list=ls())
When I define this function and call it by simply using clear(), the code executes but my workspace is not cleared. I tried various formats of defining the function to see if anything funky was going on, but it all gives the same result. Simply using the rm(list=ls()) function works, but not when I embed it in my function. Can anyone point me in the right direction? And what am I not understanding about user-defined R functions?
Thanks!
The problem is that when you call ls() inside a function it returns the objects in the environment of that function by default. Same with rm().
Try this:
clear <- function() {
rm(list=ls(.GlobalEnv), envir=.GlobalEnv)
}
I am writing some data manipulation scripts in R, and I finally decided to create an external .r file and call my functions from there. But it started giving me some problems when I try calling some functions. Simple example:
This one works with no problem:
change_column_names <- function(file,new_columns,seperation){
new_data <- read.table(file, header=TRUE, sep=seperation)
colnames(new_data) <- new_columns
write.table(new_data, file=file, sep=seperation, quote=FALSE, row.names = FALSE)
}
change_column_names("myfile.txt",c("Column1", "Column2", "Cost"),"|")
When I crate a file "data_manipulation.r", and put the above change_column_names function in there, and do this
sys.source("data_manipulation.r")
change_column_names("myfile.txt",c("Column1", "Column2", "Cost"),"|")
it does not work. It gives me could not find function "read.table" error. I fixed it by changing the function calls to util:::read.table and util:::write.table .
But this kinda getting frustrating. Now I have the same issue with the aggregate function, and I do not even know what package it belongs to.
My questions: Which package aggregate belongs to? How can I easily know what packages functions come from? Any cleaner way to handle this issue?
The sys.source() by default evaluates inside the base environment (which is empty) rather than the global environment (where you usually evaluate code). You probably should just be using source() instead.
You can also see where functions come from by looking at their environment.
environment(aggregate)
# <environment: namespace:stats>
For the first part of your question: If you want to find what package a function belongs to, and that function is working properly you can do one of two (probably more) things:
1.) Access the help files
?aggregate and you will see the package it belongs to in the top of the help file.
Another way, is to simply type aggregate without any arguments into the R console:
> aggregate
function (x, ...)
UseMethod("aggregate")
<bytecode: 0x7fa7a2328b40>
<environment: namespace:stats>
The namespace is the package it belongs to.
2.) Both of those functions that you are having trouble with are base R functions and should always be loaded. I was not able to recreate the issue. Try using source instead of sys.source and let me know if it alleviates your error.
I am attempting to over-ride the print.anova() function from the R stats package within a local package that I use when teaching. Basically, I want to remove the printing of the heading and add a "total" row without creating a new function (e.g., ANOVA()) with a new class.
The function looks like the following:
print.anova <- function(x,digits=max(getOption("digits")-2,3),
signif.stars=getOption("show.signif.stars"),totalSS=TRUE,rm.heading=TRUE,...) {
if (!any(grepl("Res.Df",colnames(x)))) { # exclusion for multiple lm objects
if (!any(grepl("Levene",attr(x,"heading")))) { # exclusion for levenes.test
if (totalSS) { # add total SS row
x <- rbind(x,c(sum(x$Df),sum(x[,"Sum Sq"]),NA,NA,NA))
row.names(x)[dim(x)[1]] <- "Total"
}
}
}
if (rm.heading) attr(x,"heading") <- NULL # remove heading
stats::print.anova(x,digits=digits,signif.stars=signif.stars,...)
invisible(x)
}
My problem is that I am not sure whether to export this as a function, a method, an S3method, some combination of those, or something else entirely. For example, when I try this (part of roxygenize code):
#'#export
I get the following warning when running Rcmd check:
S3 methods shown with full name in documentation object 'print.anova':
'print.anova'
but the function works as expected when I load my package.
However, if I try this:
#'#method print anova
#'#S3method print anova
I dont' get any warnings or errors with Rcmd check but when I try to use the function in R it finds the original function in the stats package namespace. Furthermore, if I do this
getAnywhere(print.anova)
I get this
2 differing objects matching ‘print.anova’ were found in the following places
package:stats
registered S3 method for print from namespace stats
namespace:NCStats
namespace:stats
Finally, for this version (not using export, but using method and S3method), my roxygen-developed namespace has the following item in it
S3method(print,anova)
Leading to my confusion is that I seem to have had success doing something similar with other functions (e.g., using the method and S3method version with print.summary.lm).
I would appreciate any help in my understanding what I am doing wrong here (or how I can ultimately accomplish this goal). Thank you in advance for any help.
p.s., for what it is worth, I am on Windows 7 (32-bit), R 2.15.2, and using RStudio.
Instead of trying to override the print.anova function you could create your own class which is essentially identical to the anova class. Create an as.myanova function which will turn an anova object into an object of mynanova then write your print.myanova function.