plot.predict() or predict.plot() functions cited in literature, but no longer exists - r

I am trying to use predict.plot or plot.predict (I've seen both of them referenced on various websites and I don't know which one is right).
However, in R, neither of these are valid functions. I don't know if I'm missing a package or if the sources I'm using are outdated in terms of the functions being referenced.
This site is using the function
It's very old. Can someone familiar with stats help me figure out how to do this with the latest version of R, or help me figure out how to get predict.plot/plot.predict to work?

This is a user defined function. The author of the course you linked to provides it online:
Link to R script

The S3 dispatch system for functions in R examines the class of the first argument and then calls a function with the name func.class. In this case the author has defined several plot.predict functions: predict.plot.data.frame, predict.plot.lm, and predict.plot.formula which are then given the arguments on hte basis of the class of what is (first) in the argument list. The plot.predict function is just this:
predict.plot <- function(object, ...) UseMethod("predict.plot")
The "good stuff" is in the other three functions at the link Roland provided. I do think the author's use of a dot in the name for the generic function is a bit confusing. One might have expected there to be a class "plot" for which there was a generic function predict, but that is not really the case here, although you might find it interesting to just type: methods(predict) .After you had loaded the R script on that website you could find those various functions using:
methods(predict.plot)
#[1] predict.plot.data.frame predict.plot.formula predict.plot.lm

Related

What does the QuickTbl function do in this code?

I'm wondering how the author of the following page define the "QuickTbl" function. I assumed that it’s a user-defined function, rather than a function included in a library. I could not find any definition for the QuickTbl function.
https://alphahive.wordpress.com/2014/09/25/asset-pricing-9b-regime-switching/
If you look at the blog above, in MarkovEstPlot, QuickTbl is used as follows:
gg.m.tbl <- QuickTbl(mean.tbl,title='Estimates of Mean')
This should be defined somewhere in the blog (or in a library), but I could not find any.
(I am now asking the author for his/her help as well).
install.packages("basictabler")
library(“basictabler”)
and replacing QuickTbl by qtbl seems to work now.
For the basictabler library including qtbl function, please refer to: https://cran.r-project.org/web/packages/basictabler/vignettes/v01-introduction.html

Is it unwise to modify the class of functions in other packages?

There's a bit of a preamble before I get to my question, so hang with me!
For an R package I'm working on I'd like to make it as easy as possible for users to partially apply functions inline. I had the idea of using the [] operators to call my partial application function, which I've name "partialApplication." What I aim to achieve is this:
dnorm[mean = 3](1:10)
# Which would be exactly equivalent to:
dnorm(1:10, mean = 3)
To achieve this I tried defining a new [] method for objects of class function, i.e.
`[.function` <- function(...) partialApplication(...)
However, R gives a warning that the [] method for function objects is "locked." (Is there any way to override this?)
My idea seemed to be thwarted, but I thought of one simple solution: I can invent a new S3 class "partialAppliable" and create a [] method for it, i.e.
`[.partialAppliable` = function(...) partialApplication(...)
Then, I can take any function I want and append 'partialAppliable' to its class, and now my method will work.
class(dnorm) = append(class(dnorm), 'partialAppliable')
dnorm[mean = 3](1:10)
# It works!
Now here's my question/problem: I'd like users to be able to use any function they want, so I thought, what if I loop through all the objects in the active environment (using ls) and append 'partialAppliable' to the class of all functions? For instance:
allobjs = unlist(lapply(search(), ls))
#This lists all objects defined in all active packages
for(i in allobjs) {
if(is.function(get(i))) {
curfunc = get(i)
class(curfunc) = append(class(curfunc), 'partialAppliable')
assign(i, curfunc)
}
}
Voilà! It works. (I know, I should probably assign the modified functions back into their original package environments, but you get the picture).
Now, I'm not a professional programmer, but I've picked up that doing this sort of thing (globally modifying all variables in all packages) is generally considered unwise/risky. However, I can't think of any specific problems that will arise. So here's my question: what problems might arise from doing this? Can anyone think of specific functions/packages that will be broken by doing this?
Thanks!
This is similar to what the Defaults package did. The package is archived because the author decided that modifying other package's code is a "very bad thing". I think most people would agree. Just because you can do it, does not mean it's a good idea.
And, no, you most certainly should not assign the modified functions back to their original package environments. CRAN does not like when packages modify the users search path unnecessarily, so I would be surprised if they allowed a package to modify other package's function arguments.
You could work around that by putting all the modified functions in an environment on the search path. But then you have to ensure that environment is always searched first, which means modifying the search path every time another package is loaded.
Changing arguments for functions in other packages also has the potential to make it very difficult for others to reproduce your results because they must have all your argument settings. Unless you always call functions with all their arguments specified, which defeats the purpose of what you're trying to do.

R: How do I add an extra function to a package?

I would like to add an idiosyncratically modified function to package written by someone else, with an R Script, i.e. just for the session, not permanently. The specific example is, let's say, bls_map_county2() added to the blscrapeR package. bls_map_county2 is just a copy of the bls_map_county() function with an added ... argument, for purposes of changing a few of the map drawing parameters. I have not yet inserted the additional parameters. Running the function as-is, I get the error:
Error in BLS_map_county(map_data = df, fill_rate = "unemployed_rate", :
could not find function "geom_map"
I assume this is because my function does not point to the blscrapeR namespace. How do I assign my function to the (installed, loaded) blscrapeR namespace, and is there anything else I need to do to let it access whatever machinery from the package it requires?
When I am hacking on a function in a particular package that in turn calls other functions I often use this form after the definition:
mod_func <- function( args) {body hacked}
environment(mod_func) <- environment(old_func)
But I think the function you might really want is assignInNamespace. These methods will allow the access to non-exported functions in loaded packages. They will not however succeed if the package is not loaded. So you may want to have a stopifnot() check surrounding require(pkgname).
There are two parts to this answer - first a generic answer to your question, and 2nd a specific answer for the particular function that you reference, in which the problem is something slightly different.
1) generic solution to accessing internal functions when you edit a package function
You should already have access to the package namespace, since you loaded it, so it is only the unexported functions that will give you issues.
I usually just prepend the package name with the ::: operator to the non exported functions. I.e., find every instance of a call to some_internal_function(), and replace it with PackageName:::some_internal_function(). If there are several different internal functions called within the function you are editing, you may need to do this a few times for each of the offending function calls.
The help page for ::: does contain these warnings
Beware -- use ':::' at your own risk!
and
It is typically a design mistake to use ::: in your code since the
corresponding object has probably been kept internal for a good
reason. Consider contacting the package maintainer if you feel the
need to access the object for anything but mere inspection.
But for what you are doing, in terms of temporarily hacking another function from the same package for your own use, these warnings should be safe to ignore (at you own risk, of course - as it says in the manual)
2) In the case of blscrapeR ::bls_map_county()
The offending line in this case is
ggplot2::ggplot() + geom_map(...
in which the package writers have specified the ggplot2 namespace for ggplot(), but forgotten to do so for geom_map() which is also part of ggplot2 (and not an internal function in blscrapeR ).
In this case, just load ggplot2, and you should be good to go.
You may also consider contacting the package maintainer to inform them of this error.

How to get help in R?

What is the possible documentation available for R package? For example I try to understand sp package.
In addition to help(sp), what are the other functions for searching through help and documentation?
Getting help on a function that you know the name of
Use ? or, equivalently, help.
?mean
help(mean) # same
For non-standard names use quotes or backquotes; see An Introduction to R: Getting help with functions and features:
For a feature specified by special characters, the argument must be enclosed in double or single quotes, making it a “character string”: This is also necessary for a few words with syntactic meaning including if, for and function."
?`if`
?"if" # same
help("if") # same
There are also help pages for datasets, general topics and some packages.
?iris
?Syntax
?lubridate
Use the example function to see examples of how to use it.
example(paste)
example(`for`)
The demo function gives longer demonstrations of how to use a function.
demo() # all demos in loaded pkgs
demo(package = .packages(all.available = TRUE)) # all demos
demo(plotmath)
demo(graphics)
Finding a function that you don't know the name of
Use ?? or, equivalently, help.search.
??regression
help.search("regression")
Again, non-standard names and phrases need to be quoted.
??"logistic regression"
apropos finds functions and variables in the current session-space (but not in installed but not-loaded packages) that match a regular expression.
apropos("z$") # all fns ending with "z"
rseek.org is an R search engine with a Firefox plugin.
RSiteSearch searches several sites directly from R.
findFn in sos wraps RSiteSearch returning the results as a HTML table.
RSiteSearch("logistic regression")
library(sos)
findFn("logistic regression")
Finding packages
available.packages tells you all the packages that are available in the repositories that you set via setRepositories. installed.packages tells you all the packages that you have installed in all the libraries specified in .libPaths. library (without any arguments) is similar, returning the names and tag-line of installed packages.
View(available.packages())
View(installed.packages())
library()
.libPaths()
Similarly, data with no arguments tells you which datasets are available on your machine.
data()
search tells you which packages have been loaded.
search()
packageDescription shows you the contents of a package's DESCRIPTION file. Likewise news read the NEWS file.
packageDescription("utils")
news(package = "ggplot2")
Getting help on variables
ls lists the variables in an environment.
ls() # global environment
ls(all.names = TRUE) # including names beginning with '.'
ls("package:sp") # everything for the sp package
Most variables can be inspected using str or summary.
str(sleep)
summary(sleep)
ls.str is like a combination of ls and str.
ls.str()
ls.str("package:grDevices")
lsf.str("package:grDevices") # only functions
For large variables (particularly data frames), the head function is useful for displaying the first few rows.
head(sleep)
args shows you the arguments for a function.
args(read.csv)
General learning about R
The Info page is a very comprehensive set of links to free R resources.
Many topics in R are documented via vignettes, listed with browseVignettes.
browseVignettes()
vignette("intro_sp", package = "sp")
By combining vignette with edit, you can get its code chunks in an editor.
edit(vignette("intro_sp",package="sp"))
This answer already gives you a very comprehensive list.
I would add that findFn("some search terms") in package sos is extremely helpful, if you only have an idea/keywords of what you are looking for and don't already have a package or function in mind.
And also the task views on CRAN: not really a search process but a great place to wander as you wonder.
This thread contains many good suggestions. Let me add one more.
For finding which packages are loaded, plus extra goodies, ?sessionInfo is quite nice.
help(package="<package-name>") where of course <package-name> is the name of the package you want help for.
Often the same function name is used by several packages. To get help on a function from a specific package, use:
help(aggregate, package="stats")
help(aggregate, package="sp")
In the RStudio IDE you can click on any function name and press F1, which will directly open the associated function help text in its pane. Like you would have called help() or ?fun().

Building R package: no visible global function definition for 'subject'

I'm building an R package for the first time and am having some trouble. I am doing an R CMD Check and am getting the following error:
get.AlignedPositions: no visible global function definition for 'subject'
I am not sure what is causing this. I don't even have a "subject" variable in my code. The code is rather lengthy so I rather not paste all of it unless someone asks in a comment. Is there something specific I should look for? The only thing I can think of is that I have a line like this:
alignment <-pairwiseAlignment(pattern = canonical.protein, subject=protein.extracted, patternQuality=patternQuality,
subjectQuality=subjectQuality,type = type, substitutionMatrix= substitutionMatrix,
fuzzyMatrix=fuzzyMatrix,gapOpening=gapOpening,gapExtension=gapExtension,
scoreOnly=scoreOnly)
but subject is defined by the pairwiseAlignment function in the Biostrings package. Thank you for your help!
R spotted a function, subject, being used without a function called subject being available. One possible reason for this is explained in this discussion on R-devel. In that case code is used conditionally, e.g. if a certain package is installed we use its functionality. When checking the package on a system which does not have this package installed, we run in to these kinds of warnings. So please check if this might be the case. Alternatively, you might have made a mistake by calling subject while no function existed, e.g. subject was not a function but just an object.

Resources