How to tell RStudio to autocomplete my function's arguments with package names? - r

According to RStudio:
In addition, certain functions, such as library() and require(), expect package names for completions. RStudio automatically infers whether a particular function expects a package name and provides those names as completion...
My question is: how? I'm writing a custom function that takes package names as arguments, yet RStudio's only completing the arguments with object & function names, and I can't tell what it is about the library() and require() code that RStudio is picking up on.
My function is:
unpack <- function(...,
lib = NULL,
repos = getOption("repos")) {
pkgs <- sapply(match.call(expand.dots = TRUE)[-1], as.character)
new.pkgs <-
pkgs[!(
pkgs %in% installed.packages(lib.loc = lib)[, "Package"]
)]
if (length(new.pkgs))
install.packages(new.pkgs,
lib = lib,
repos = repos)
sapply(pkgs, require,
lib.loc = lib,
character.only = TRUE)
}

As #hrbrmstr pointed out, there's both Java and R code that specifically name the four functions that autocomplete with package names, so the solution is to either mask one of those and cross your fingers, or add your function's name to those lists in both source files (or maybe just the R, I wonder).

I recently created a package which has few more autocompletion (though totally experimental) (as extra code only).
It can be seen here https://github.com/r-rudra/patch/blob/main/inst/embedded/usecases.R
Maybe soon enough all these will be available by default in RStudio.
Check this comment

Related

loading multiple R packages stored as an object using pacman's p_load

I'd like to use pacman's p_load function. I've read through the documentation and understand how to pass multiple packages into the function directly. However, I'd like to store the package names separately and feed them into pacman so that I can use this same 'list' to later test that the packages have been loaded into the environment.
Based on the documentation, pacman is expecting a character vector. my first attempt was:
pkg_list <- as.vector(c("tidyverse", "forecast")
or
pkg_list <- "tidyverse, forecast"
followed by:
pacman::p_load(pkg_list)
or
pacman::p_load(pkg_list, character.only = FALSE)
Which all return the same error stating:
package ‘pkg_list’ is not available
Fine, it's obviously looking for a package called pkg_list instead of the contents of the object so I also tried using a list and unlisting it in the p_load statement, using eval, etc. but p_load always seems to evaluate whatever is input as a literal.
Just trying to better understand why and how to escape that literal evaluation if possible.

How to find out if I am using a package

My R script has evolved over many months with many additions and subtractions. It is long and rambling and I would like to find out which packages I am actually using in the code so I can start deleting library() references. Is there a way of finding redundant dependencies in my R script?
I saw this question so I tried:
library(mvbutils)
library(MyPackage)
library(dplyr)
foodweb( funs=find.funs( asNamespace( 'EndoMineR')), where=
asNamespace( 'EndoMineR'), prune='filter')
But that really tells me where I am using a function from a package whereas I don't necessarily remember which functions I have used from which package.
I tried packrat but this is looking for projects whereas mine is a directory of scripts I am trying to build into a package.
To do this you first parse your file and then use getAnywhere to check for each terminal token in which namespace it is defined. Compare the result with the searchpath and you will have the answer. I compiled a function that takes a filename as argument and returns the packages which are used in the file. Note that it can only find packages that are loaded when the function is executed, so be sure to load all "candidates" first.
findUsedPackages <- function(sourcefile) {
## get parse tree
parse_data <- getParseData(parse(sourcefile))
## extract terminal tokens
terminal_tokens <- parse_data[parse_data$terminal == TRUE, "text"]
## get loaded packages/namespaces
search_path <- search()
## helper function to find the package a token belongs to
findPackage <- function(token) {
## get info where the token is defined
token_info <- getAnywhere(token)
##return the package the comes first in the search path
token_info$where[which.min(match(token_info$where, search_path))]
}
packages <- lapply(unique(terminal_tokens), findPackage)
##remove elements that do not belong to a loaded namespace
packages <- packages[sapply(packages, length) > 0]
packages <- do.call(c, packages)
packages <- unique(packages)
##do not return base and .GlobalEnv
packages[-which(packages %in% c("package:base", ".GlobalEnv"))]
}

How to know to which package a particular function belongs to in R prior to package loading?

Example, I know many popular functions, to name one like tbl_df(). I usually do not remember which package it belongs to i.e. data.table or dplyr. So I have to always remember and load a package and I can not do ?tbl_df unless I have loaded the correct package.
Is there a way to know to which package a particular function belongs to, prior to loading or installing of the package in R console itself.
Any help is highly appreciated.
Thanks.
sos package can help!
Try:
install.packages("sos")
library(sos)
findFn("str_replace")
Try this as well
lsp <- function(package, all.names = FALSE, pattern)
{ package <- deparse(substitute(package)) ls( pos = paste("package", package, sep = ":"),
all.names = all.names, pattern = pattern ) }
after running this function, if you want to search for str_replace function in stringr package- lsp(stringr, pattern="*replace")
Inspired by #J_F who suggested ??tbl_df: I was looking for 'arima' and had dozens if not hundreds of hits; I narrowed them down using
help.search('arima', fields=c('name'), ignore.case=FALSE, agrep=FALSE)
(most importantly, agrep=FALSE turns off fuzzy matching)

extracting source code from r package

I am trying to install the r package sowas and unfortunately it is too old to implement in the new versions of r.
According to the author you can use the package using the source() function to gain access to the code but I have not been able to figure out how to do that.
Any help is appreciated.
Here is a link to the package I described as it is not a CRAN package: http://tocsy.pik-potsdam.de/wavelets/
The .zip file is a windows binary and as such it won't be too interesting. What you'll want to look at is the contents of the .tar.gz archive. You can extract those contents and then look at the code in the R subdirectory.
You could also update the package to work with new versions of R so that you can actually build and install the package. To do so you could unpack the .tar.gz as before but now you'll need to add a NAMESPACE file. This is just a plaintext file at the top of the package directory that has a form like:
export(createar)
export(createwgn)
export(criticalvaluesWCO)
export(criticalvaluesWSP)
export(cwt.ts)
export(plot.wt)
export(plotwt)
export(readmatrix)
export(readts)
export(rk)
export(wco)
export(wcs)
export(writematrix)
export(wsp)
Where you have an export statement for any function in the package that you actually want to be able to use. If a function isn't exported then the functions in the package still have access to that function but the user can't use it (as easily). Once you do that you should be able to build and install the package.
I took the liberty of doing some of this already. I haven't actually taken the time to figure out which functions are useful and should be exported and just assumed that if a help page was written for the function that it should be exported and if there wasn't a help page then I didn't export it. I used Rd2roxygen to convert the help pages to roxygen code (because that's how I roll) and had to do a little bit of cleanup after that but it seems to install just fine.
So if you have the devtools package installed you should actually be able to install the version I modified directly by using the following commands
library(devtools)
install_github("SOWAS", "Dasonk")
Personally I would recommend that you go the route of adding the NAMESPACE file and what not directly as then you'll have more control over the code and be more able to fix any problems that might occur when using the package. Or if you use git you could fork my repo and continue fixing things from there. Good luck.
If you want to see the source code of a particular function, then just type the name of the function without the braces and press enter. You will see the code.
For example type var in command prompt to see it's code.
> var
function (x, y = NULL, na.rm = FALSE, use)
{
if (missing(use))
use <- if (na.rm)
"na.or.complete"
else "everything"
na.method <- pmatch(use, c("all.obs", "complete.obs", "pairwise.complete.obs",
"everything", "na.or.complete"))
if (is.na(na.method))
stop("invalid 'use' argument")
if (is.data.frame(x))
x <- as.matrix(x)
else stopifnot(is.atomic(x))
if (is.data.frame(y))
y <- as.matrix(y)
else stopifnot(is.atomic(y))
.Call(C_cov, x, y, na.method, FALSE)
}
<bytecode: 0x0000000008c97980>
<environment: namespace:stats>

knowing functions and dataset available in a package without any manual and information (blackbox) R

I have a package which is beta version, I do not have manual neither helppage have a manual.
using following command, I can say that the package is loaded in current session.
(.packages())
When I search
data()
I can not see any data associated with. Is that mean that there is no dataset associate with it ? How can I know whether there are any functions?
function() # do not work.
To list all stuff,
ls("package:MASS", all = TRUE)
all = TRUE shows hidden objects (i.e., variable name beginning with ".")
To list all functions with formals,
lsf.str("package:MASS", all = TRUE)
To list all datasets with brief description
data(package = "MASS")$results
Just in case, to list all imports and exports of the namespace,
getNamespaceInfo("MASS", "imports")
From the help page for ?data
try(data(package = "rpart") ) # list the data sets in the rpart package
And this is one of the reasons why the uses of the name 'data' is deprecated.
try(fortunes::fortune("dog") )

Resources