Determine name of R package my code is in? - r

I'm working on an R package and (in the package's code) need to determine the version number when a certain function is called.
packageVersion("mypackage") works, but I'd rather not hard code the name of the package. How can I ask "what's the name of the package I'm in"? (Or directly get the version number of the package I'm in.)

This mailing list thread describes packageName().
(As Martin pointed out in comments.)

I have not handled working with packages. But I am assuming you can use something like
packageVersion(getPackageName())
While you can supply parameters to getPackageName to search for the package name you are looking for, I think just supplying it without any parameters will get the current environment, (and in your case) the current package.
Source:
The R Reference Index, available at https://cran.r-project.org/manuals.html

Related

How to determine the package that defines a particular identifier?

When reading source code written by others, it is often difficult for me to figure out what package a particular identifier (typically a function) comes from. (This is because such code "imports" identifiers through statements of the form library(...), which enables the use in the code of the imported identifiers without having to provide a package qualifier.)
Is there a simple way to determine the package a particular identifier comes from?
You can use the function getAnywhere(). Try this:
library(dplyr)
getAnywhere("%>%")$where
This tells you both the package and the namespace:
[1] "package:dplyr" "namespace:magrittr"

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().

How can I remove a lock from a linked environment in R?

I tried to run a Bioconductor package (truncateCDF) that modify an environment(hgu133plus2cdf), to remove unwanted probesets, from an affymetrix chip.
Everything went fine, until I got the following message (translated from french):
> assign(cdfname, cdf.env, env=CDF.env)
Error in assign(cdfname, cdf.env, env = CDF.env) :
impossible to change the value of a locked link for 'hgu133plus2cdf'
The assign function is the ultimate function of the code, that save the changes made to the environment dataset CDF.env to the original environment (hgu133plus2cdf), before using it in analyses of affymetrix chip results; so, it is essential.
My question: what is this locked link to the hgu133plus2cdf environment, and how could I bypass it.
The author of this package successfully run its package around 2005; so I suppose it is a feature introduced since then in R (probably not related to Bioconductor, since assign is a basic R function, reason why I ask this question on this forum instead of Biostar).
I tried to read the docs, but I am overwhelmed, when it comes to environments.
Thanks in advance for any help.
I don't think truncateCDF is from a Bioconductor package; it is a at least not current. This sounds like this post and the next two from the same thread from the Bioconductor mailing list. It is a result of a change in R -- packages now have not-easily-modified name spaces, and these are implemented by locking the environment in which name space symbols are defined. Removing probes is not an essential part of a typical microarray work flow. Please ask on the Bioconductor mailing list (no subscription required) if you'd like more help.

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.

Embed fix() function within .R script?

I am looking for a way to embed the fix() function within a script. Basically, here's what I'm currently doing:
I load a certain package. For example, library(PerformanceAnalytics)
I call the fix() function to edit a couple functions within the loaded package. Example, fix(VaR).
Then, using R's built-in editor, I copy-paste my function over the one originally loaded from the package.
Finally, I source in my .R script which calls the above functions I fixed and performs the computations I need.
Essentially, I'd like to streamline Step 3 above. Rather than having to manually type fix(function) and copy-paste over the original functions within the loaded package, I'd rather just have it done within a script I source.
Is there anyway to accomplish this?
FYI, I have reached out to the package's creator and loading a re-compiled version of the package with my modified code is out of the question.
Maybe source your functions and then use assignInNamespace?
EDIT #1:
The above won't work because assignInNamespace doesn't alter objects that have been exported. Instead,
put your functions in a file (foo.R)
load the package
then source(foo.R) or
sys.source(foo.R, envir=attach(NULL, name="myenv"))
Your functions will be higher up on the search list if you load them after the package, so R will find them before getting to the package's functions with the same name.
EDIT #2:
I didn't realize VaR called unexported functions in the namespace. That's why EDIT #1 doesn't work. To get it to work, you would need to explicitly reference all unexported PerformanceAnalytics functions used in VaR (e.g. change VaR.Gaussian to PerformanceAnalytics:::VaR.Gaussian).
See this post on R-devel for a couple other approaches. I couldn't quickly get Prof. Ripley's solution to work (I get the same error as in EDIT #1) and I didn't try Gabor's solution.
You can edit the body directly, discussed here:
What ways are there to edit a function in R?
You can download the packages source from CRAN. Edit the function (it will be found in PackageName/R), then install this package into R and just use it that way.
You can even change the package name in the DESCRIPTION file ... call it "PerformanceAnalytics2", then in R you just library(PerformanceAnalytics2) and use it as you would the original package.

Resources