Why does wrapper function result in error - r

I'm trying to include a function from the Bioconductor package "simpIntLists" in my own package. "import(simpIntLists)" is added to the Namespace file.
However, the function results in an error
do_xy <- function(organism, IDType){
network <- simpIntLists::findInteractionList(organism, IDType)
}
do_xy("human", "EntrezId")
#Error message
data set ‘HumanBioGRIDInteractionEntrezId’ not foundError in get("HumanBioGRIDInteractionEntrezId") :
object 'HumanBioGRIDInteractionEntrezId' not found
# results in the same error (outside of the function)
simpIntLists::findInteractionList(organism, IDType)
It works fine when simpIntLists is attached
# works
library(simpIntLists)
network <- simpIntLists::findInteractionList(organism, IDType)

I saw the code here (https://bioconductor.org/packages/release/data/experiment/html/simpIntLists.html).
This code does not seem to take into account the situation where the package is used without installation.
For your information, the relevant part to this error is around the line 52.
else if (organism == 'human'){
if (idType == 'EntrezId'){
data(HumanBioGRIDInteractionEntrezId);
interactionList <- get("HumanBioGRIDInteractionEntrezId");
}
It tries to fetch the data to the namespace but it fails to do so if the package is not imported via library yet. This only generates a warning. The error then occurs when it tries to use the data because it does not exist in the namespace.
A workaround is that you import the data in your code explicitly. Then you can use the function as below. Note that the warning remains because of the embedded package code. If the warning is annoying, use suppressWarnings.
data(HumanBioGRIDInteractionEntrezId, package="simpIntLists")
simpIntLists::findInteractionList("human", "EntrezId")

Related

PreprocessCore package

I'm quite new to R and I got an assignment that includes a sourcecode.
Part of the source code includes the following line:
library(preprocessCore)
Then I have in my source code a definition of the following function:
quantile.normalize.raw.gtex <- function(edata.mat)
{
norm_edata = normalize.quantiles(as.matrix(edata.mat))
rownames(norm_edata) = rownames(edata.mat)
colnames(norm_edata) = colnames(edata.mat)
return(norm_edata)
}
Finally, I have an object being initialized to the output of this function, after sending a predefined parameter:
tissue.edata.qn = quantile.normalize.raw.gtex(tissue.edata)
From what I understand, the library function is supposed to include the function normalize.quantiles, which is called in the function that is defined in my source code.
However, when I run the line library(preprocessCore) I get the following error:
Error in library(preprocessCore) :
there is no package called ‘preprocessCore’
I also tried to run the rest of the code and got the error:
Error in normalize.quantiles(as.matrix(edata.mat)) :
could not find function "normalize.quantiles"
I looked for the preprocessCore online and eventually I tried to write install.packages("preprocessCore"), but I got a warning message that this package is only available in version 3.6.0 of R, even though I checked and this is the version that I have.
If somebody has any idea what the problem is, I will appreciate your help.
Thanks in advance
The preprocessCore package is available in Bioconductor. So, to install it, you need the following lines:
source("http://bioconductor.org/biocLite.R")
biocLite("preprocessCore")
After that, you can load the package using library(preprocessCore)
Hope it helps.

Getting an error could not find function in a for loop

I'm running the following code:
dat1 <- returns
for (j in 1:12) set(dat1, j = j, value = wind(dat1[[j]]))
And getting the following error message:
Error in wind(dat1[[j]]) : could not find function "wind"
My search for a solution mainly involves packages that aren't properly installed. I'm not 100% sure but I think it isn't related to that.
Best
To check if the function is really loaded into the namespace you have to try to
print the function:
print(wind)
Error in print(wind) : object 'wind' not found
You have to look if the package is correctly loaded
library("foo")
Check package dependency in case of error.
I use the findFn-function in sos-package to search for function names. Unfortunately dataset names also appear in the same column:
install.packages("sos")
library(sos)
findFn("wind")
There is a wind function (or dataset name) in packages: gstat, ismev, NPCirc, BAMBI, ggmap, gcookbook, CircOutlier, plotly, and circular.

Function imported from dependency not found, requires library(dependency)

I am trying to create an R package that uses functions from another package (gamlss.tr).
The function I need from the dependency is gamlss.dist::TF (gamlss.dist is loaded alongside gamlss.tr), but it is referenced in my code as simply TF within a call to gamlss.tr::gen.trun.
When I load gamlss.tr manually with library(), this works. However, when I rely on the functions of the dependency automatically being imported by my package through #import, I get an "object not found" error as soon as TF is accessed.
My attempt to be more explicit and reference the function I need as gamlss.dist::TF resulted in a different error ("unexpected '::'").
Any tips on how to use this function in my package would be much appreciated!
The code below reproduces the problem if incorporated into a clean R package (as done in this .zip), built and loaded with document("/path/to/package"):
#' #import gamlss gamlss.tr gamlss.dist
NULL
#' Use GAMLSS
#'
#' Generate a truncated distribution and use it.
#' #export
use_gamlss <- function() {
print("gen.trun():")
gamlss.tr::gen.trun(par=0,family=TF)
#Error in inherits(object, "gamlss.family") : object 'TF' not found
#gamlss.tr::gen.trun(par=0,family=gamlss.dist::TF)
#Error in parse(text = fname) : <text>:1:1: unexpected '::'
y = rTFtr(1000,mu=10,sigma=5, nu=5)
print("trun():")
truncated_dist = gamlss.tr::trun(par=0,family=TF, local=TRUE)
model = gamlss(y~1, family=truncated_dist)
print(model)
}
use_gamlss() will only start working once a user calls library(gamlss.tr).
This is due to bad design of gamlss.tr in particular the trun.x functions (they take character vectors instead of family objects / they evaluate everything in the function environment instead of the calling environment).
To work around this, you have to make sure that gamlss.distr is in the search path of the execution environment of gamlss.tr functions (This is why ## import-ing it in your package does not help: it would need to be #' #import-ed in gamlss.tr).
This can be achieved by adding it to Depends: of your package.
If you want to avoid that attaching your package also attaches gamlss.distr, you could also add the following at the top of use_gamlss:
nsname <-"gamlss.dist"
attname <- paste0("package:", nsname)
if (!(attname %in% search())) {
attachNamespace(nsname)
on.exit(detach(attname, character.only = TRUE))
}
This would temporarily attach gamlss.dist if it is not attached already.
You can read more on namespaces in R in Hadley Wickham's "Advanced R"

Error : could not find function "ImportMethodFrom"

I tried to run the code in Chapter 7 Data mining with R learning with case study book but I got an error in following line:
rankWorkflows(svm, maxs = TRUE)
The error was:
Error in as.character.default(X[[i]], ...) : no method for coercing
this S4 class to a vector
Then I searched on the internet and found following solution:
importMethodsFrom(GenomicRanges, as.data.frame)
and again again I got a new error:
Error: could not find function "importMethodFrom"
I searched a lot but I got nothing :(
You can try using library(sos) to find the packages where your function is located.
library(sos)
findFn("replaceherewithyourfunction")
Based on the answer of #Bea, there does not seem to be a importMethodsFrom anywhere in R. My guess is you found the call in a NAMESPACE file. Those files have different syntax than normal R scripts.
If you want to load a specific function from an R package (rather than all functions from a package), you can use libraryname::functionname instad of functionname in your code. In your case, replace as.data.frame with GenomicRanges::as.data.frame
If this does not work (for example because you don't have as.data.frame anywhere in your code), you can also load the whole GenomicRanges library with library(GenomicRanges)

Retrieving expected data.frame for testthat expectation

I'd like to test that a function returns the expected data.frame. The data.frame is too large to define in the R file (eg, using something like structure()). I'm doing something wrong with the environments when I try a simple retrieval from disk, like:
test_that("SO example for data.frame retreival", {
path_expected <- "./inst/test_data/project_longitudinal/expected/default.rds"
actual <- data.frame(a=1:5, b=6:10) #saveRDS(actual, file=path_expected)
expected <- readRDS(path_expected)
expect_equal(actual, expected, label="The returned data.frame should be correct")
})
The lines execute correctly when run in the console. But when I run devtools::test(), the following error occurs when the rds/data.frame is read from a file.
1. Error: All Records -Default ----------------------------------------------------------------
cannot open the connection
1: withCallingHandlers(eval(code, new_test_environment), error = capture_calls, message = function(c) invokeRestart("muffleMessage"),
warning = function(c) invokeRestart("muffleWarning"))
2: eval(code, new_test_environment)
3: eval(expr, envir, enclos)
4: readRDS(path_expected) at test-read_batch_longitudinal.R:59
5: gzfile(file, "rb")
To make this work, what adjustments are necessary to the environment? If there's not an easy way, what's a good way to test large data.frames?
I suggest you check out the excellent ensurer package. You can include these functions inside the function itself (rather than as part of the testthat test set).
It will throw an error if the dataframe (or whatever object you'd like to check) doesn't fulfill your requirements, and will just return the object if it passes your tests.
The difference with testthat is that ensurer is built to check your objects at runtime, which probably circumvents the entire environment problem you are facing, as the object is tested inside the function at runtime.
See the end of this vignette, to see how to test the dataframe against a template that you can make as detailed as you like. You'll also find many other tests you can run inside the function. It looks like this approach may be preferable over testthat in this case.
Based on the comment by #Gavin Simpson, the problem didn't involve environments, but instead the file path. Changing the snippet's second line worked.
path_qualified <- base::file.path(
devtools::inst(name="REDCapR"),
test_data/project_longitudinal/expected/dummy.rds"
)
The file's location is found whether I'm debugging interactively, or testthat is running (and thus whether inst is in the path or not).

Resources