R / devtools / roxygen2 : difficulty creating package - r

I'm trying to turn this function found here into an R package. I'm following the directions found here.
Here are the steps I take:
1) Load required library
library(devtools)
2) Go to a new location
setwd('C:\\myRpkgs\\')
3) Create skeleton
create('conveniencePkg')
4) Copy function to file and save in 'C:\\myRpkgs\\conveniencePkg\\R\\lsos.R'
5) Run document function
setwd("./conveniencePkg")
document()
6) Install package
setwd("..")
install("conveniencePkg")
7) Load library
library(conveniencePkg)
8) try to use lsos function
>lsos()
Error in is.na(obj.dim)[, 1] : subscript out of bounds
Result is the following error:
> traceback()
2: .ls.objects(..., order.by = "Size", decreasing = TRUE, head = TRUE,
n = n)
1: conveniencePkg::lsos()
The function runs fine if I put it into an R file and just use the source() function. Anything seem incorrect in the above steps?

Related

R package development - Calling a function that renders a Rmarkdown file that uses `dplyr`? Mask errors

I am currently developing an R package and all the functions are working nicely except one. This problematic function was meant to render a Rmarkdown file for generating a final overview.
This Rmarkdown calls other functions from my package, but then for some reason, they do not work as expected when rendering the Rmarkdown.
Here's the function that renders my Rmarkdown:
#' #importFrom rmarkdown render
#' #export
quality_report <- function(data_folder = "test/test_dataset/sanger_sequences", outputfile = "QC_report.html", output_dir = "test/", processors = 1) {
input <- system.file("rmd", "HC_report.Rmd", package = "RepertoiR")
render(input,
output_dir = output_dir,
params = list(
data_folder = data_folder,
output_dir = output_dir,
processors = processors
),
output_file = outputfile
)
}
Here's the beginning of the Rmarkdown chunk where I get the error:
library(mypackage)
# Function to summarise result that works fine outside the Rmarkdown file
sf <- summarise_quality(folder_sequences = data_folder,
secondary.peak.ratio = 0.33,
trim.cutoff = 0.01,
processors = processors)
# If-conditional to try to stop knitting if the first function does not generate a data.frame as expected
if (is.null(dim(sf[["summaries"]]))) {
print("No files were processed, knitting was stopped early.")
knitr::knit_exit()
}
sf_summaries <- sf[["summaries"]]
# Use dplyr to just filter a random variable that should be present in the df
sf_filtered <- sf_summaries %>%
filter(raw.length >= 400)
ERROR:
Quitting from lines 61-104 (HC_report.Rmd)
Error in `filter()`:
! Problem while computing `..1 = raw.length >= 400`.
Caused by error in `mask$eval_all_filter()`:
! object 'raw.length' not found
Backtrace:
1. sf_summaries %>% filter(raw.length >= 400)
3. dplyr:::filter.data.frame(., raw.length >= 400)
4. dplyr:::filter_rows(.data, ..., caller_env = caller_env())
5. dplyr:::filter_eval(dots, mask = mask, error_call = error_call)
7. mask$eval_all_filter(dots, env_filter)
I thought it was some error regarding the masking so I have tried .data$raw.length to
see if it would work, but without success:
Error in `filter()`:
! Problem while computing `..1 = .data$raw.length >= 400`.
Caused by error in `.data$raw.length`:
! Column `raw.length` not found in `.data`.
Backtrace:
1. sf_summaries %>% filter(.data$raw.length >= 400)
11. rlang:::abort_data_pronoun(x, call = y)
I am almost thinking that dplyr does not work for development inside Rmarkdown files, I have functions that use dplyr and they work fine, I could fix errors by using .data for masking. Do you have any recommendations of what might be the issue or advice regarding functions to render Rmarkdown files?

R reticulate package and python sub-modules

When trying to mimic some python code using R's reticulate package:
import_from_path("jwt_auth", "C:/Program Files/Python 3.5/Lib/site-packages/boxsdk/auth")
I get this error:
Error in py_module_import(module, convert = convert) :
SystemError: Parent module '' not loaded, cannot perform relative import
Detailed traceback:
File "C:\Program Files\Python 3.5\Lib\site-packages\boxsdk\auth\jwt_auth.py", line 13, in <module>
from .oauth2 import OAuth2
Is there a better way to load sub-modules in R like such:
from boxsdk import JWTAuth
I haven't seen any solid solution. In the package I do something like this. Interestingly the drill down of reportlab can be done with dot notation.
# this is needed in case we use python in the R code rather than source_python
fitz <- NULL
pdfr <- NULL
pdfw <- NULL
repl <- NULL
.onLoad <- function(libname, pkgname) {
# this will fail in package check
reticulate::use_condaenv(condaenv = "myenv", required = TRUE)
fitz <<- reticulate::import("fitz", delay_load = TRUE)
pdfr_0 <- reticulate::import("PyPDF2", delay_load = TRUE)
pdfr <<- pdfr_0$PdfFileReader
pdfw <<- pdfr_0$PdfFileWriter
repl <- reticulate::import("reportlab.pdfgen.canvas", delay_load = TRUE)
}

R6Class bug __Deferred_Default_Marker__

I'm implementing a new R6Class and trying to add new members dynamically (https://cran.r-project.org/web/packages/R6/vignettes/Introduction.html#adding-members-to-an-existing-class) but I get this error "__Deferred_Default_Marker__" (whether it be dynamic or not) when I implement the getx2 function.
Simple <- R6Class("Simple",
public = list(
x = 1,
getx = function() self$x,
getx2 = function() return(self$x * 2)
)
)
# To replace an existing member, use overwrite=TRUE
Simple$set("public", "x", 10, overwrite = TRUE)
s <- Simple$new()
s$getx2() # this returns "__Deferred_Default_Marker__"
Any ideas on this? It's exactly like in the documentation
The solution was to update the package. The problem with the following instruction:
devtools::install_github('r-lib/R6', build_vignettes = FALSE)
was it threw me the following error: namespace 'R6' is imported by 'CompatibilityAPI', 'mrsdeploy' so cannot be unloaded"
so i closed RStudio, and opened R.exe (C:\Program Files\R\R-3.3.3\bin) and ran the same command. Now, I have this package:
Package: R6
Version: 2.2.2.9000
URL: https://github.com/r-lib/R6/
and it works as in the specification.

dplyr clashes with testthat package when matches is used

I am getting an error because testthat::matches clashes with dplyr::matches, and I want to know how to use testthat::test_file to check functions which contain calls to matches(), without having to specify dplyr::matches in the function body.
E.g.:
> testthat::test_file('tmp_fn_testthat_test.R')
Attaching package: ‘testthat’
The following object is masked from ‘package:dplyr’:
matches
The following object is masked from ‘package:purrr’:
is_null
Show Traceback
Rerun with Debug
Error in -matches("tmp") : invalid argument to unary operator In addition: Warning message:
package ‘testthat’ was built under R version 3.2.5
DONE =========================================================================================================================================
This error can be reproduced by saving the following code in a file called tmp_fn_testthat_test.R in your working directory, and running the command testthat::test_file('tmp_fn_testthat_test_20161115.R'). Note that sourcing or running the expect_equal command while testthat is not loaded makes the test pass.
tmp_fn <- function() {
tmp_df <- data.frame(tmp_a = 1, tmp_b = 2)
tmp_df %>%
select(-matches('tmp')) %>%
ncol
}
testthat::expect_equal(tmp_fn(), 0)
This is a known issue with dplyr 0.5. The recommended solution is to use an explicit namespace prefix: dplyr::matches.
A work around appears to be commenting out the library(testthat) in the definition of testthat::test_file, and making function calls explicit (not sure whether this will have bad side effects):
my_test_that_file <- function (path, reporter = "summary", env = testthat::test_env(), start_end_reporter = TRUE,
load_helpers = TRUE)
{
# library(testthat)
reporter <- testthat:::find_reporter(reporter)
if (load_helpers) {
testthat:::source_test_helpers(dirname(path), env = env)
}
lister <- testthat:::ListReporter$new()
if (!is.null(reporter)) {
reporter <- testthat:::MultiReporter$new(reporters = list(reporter,
lister))
}
else {
reporter <- lister
}
testthat::with_reporter(reporter = reporter, start_end_reporter = start_end_reporter,
{
lister$start_file(basename(path))
testthat::source_file(path, new.env(parent = env), chdir = TRUE)
testthat:::end_context()
})
invisible(lister$get_results())
}

Why can't I vectorize source_url in knitr?

I am trying to vectorize this call to source_url, in order to load some functions from GitHub:
library(devtools)
# Find ggnet functions.
fun = c("ggnet.R", "functions.R")
fun = paste0("https://raw.github.com/briatte/ggnet/master/", fun)
# Load ggnet functions.
source_url(fun[1], prompt = FALSE)
source_url(fun[2], prompt = FALSE)
The last two lines should be able to work in a lapply call, but for some reason, this won't work from knitr: to have this code work when I process a Rmd document to HTML, I have to call source_url twice.
The same error shows up with source_url from devtools and with the one from downloader: somehwere in my code, an object of type closure is not subsettable.
I suspect that this has something to do with SHA; any explanation would be most welcome.
It has nothing to do with knitr or devtools or vectorization. It is just an error in your(?) code, and it is fairly easy to find it out using traceback().
> library(devtools)
> # Find ggnet functions.
> fun = c("ggnet.R", "functions.R")
> fun = paste0("https://raw.github.com/briatte/ggnet/master/", fun)
> # Load ggnet functions.
> source_url(fun[1], prompt = FALSE)
SHA-1 hash of file is 2c731cbdf4a670170fb5298f7870c93677e95c7b
> source_url(fun[2], prompt = FALSE)
SHA-1 hash of file is d7d466413f9ddddc1d71982dada34e291454efcb
Error in df$Source : object of type 'closure' is not subsettable
> traceback()
7: which(df$Source == x) at file34af6f0b0be5#14
6: who.is.followed.by(df, "JacquesBompard") at file34af6f0b0be5#19
5: eval(expr, envir, enclos)
4: eval(ei, envir)
3: withVisible(eval(ei, envir))
2: source(temp_file, ...)
1: source_url(fun[2], prompt = FALSE)
You used df in the code, and df is a function in the stats package (density of the F distribution). I know you probably mean a data frame, but you did not declare that in the code.

Resources