How to fix "Unable to find GhostScript executable to run checks on size reduction" error upon package check in R? - r

In Revolution R Enterprise console,
devtools::check("C:/Users/User/Documents/Revolution/mypackage")
produced
checking sizes of PDF files under 'inst/doc' ... NOTE
Unable to find GhostScript executable to run checks on size reduction
with no any other warnings/errors/notes. So, (even though AFAIK this note is not that much important for eventual check), I wanted to get rid of this warning (since I wanna put .PDF files into mypackage\inst\doc folder produced outside of R).
I have Ghostscript installed in my notebook. I got helped via:
> help("R_GSCMD")
R_GSCMD: Optional. The path to Ghostscript, used by dev2bitmap, bitmap and embedFonts.
Consulted when those functions are invoked.
Since it will be treated as if passed to system, spaces and shell metacharacters should be escaped.
> Sys.getenv("R_GSCMD")
[1] ""
What I did (and took error again) is:
> Sys.setenv("R_GSCMD") <- "C:\\Program Files (x86)\\gs\\gs9.19\\bin\\gswin32c.exe"
Error in Sys.setenv("R_GSCMD") <- "C:\\Program Files (x86)\\gs\\gs9.19\\bin\\gswin32c.exe" :
target of assignment expands to non-language object
Upon deepening, I found: ["These errors occur when one tries to assign a value to a variable that doesn't exist, or that R can't treat as a name. (A name is a variable type that holds a variable name."]
What I am basically trying to do is to set my GS executable (C:\Program Files (x86)\gs\gs9.19\bin\gswin32c.exe) to "R_GSCMD".
Any help would be greatly appreciated.

On consulting ?Sys.setenv it confirms my expectation that the call should instead be:
Sys.setenv(R_GSCMD = "C:\\Program Files (x86)\\gs\\gs9.19\\bin\\gswin32c.exe")

Because the gs versions change all the time, you may like a little R script for it!
system.partition = 'c:'
dirs = c('Program Files', 'Program Files (x86)')
for (dir in dirs) {
dir.list = list.dirs(file.path(system.partition, dir), recursive = FALSE)
GsinList = grepl(pattern = 'gs', x = dir.list)
if (sum(GsinList) > 0) {
gsDirectory = which(GsinList == TRUE)
GsExeFiles = list.files(
dir.list[gsDirectory],
recursive = TRUE,
pattern = 'gswin',
include.dirs = TRUE,
full.names = TRUE
)[1]
message('Gs found! ~> ',GsExeFiles)
Sys.setenv(R_GSCMD = GsExeFiles)
break
}
}
Gs found! ~> c:/Program Files/gs/gs9.21/bin/gswin64.exe

Related

Error in: Could not find a root 'DESCRIPTION' file that starts with '^Package'

I'm developing a shinyapp with golem. From my computer everything works perfectly, but then I loaded the package on github and installed on another computer. The app has two main parts: the first where you can process raw data and save the output as a .rds file, and the second where you can analyze the elaborated data (you can also upload a .rds file already processed). The problem is in the first part and when I have to read multiple files. It gives me this error:
Error in: Could not find a root 'DESCRIPTION' file that starts with '^Package' in 'C:\Users\Della Rocca\Documents'.
Are you in your project directory, and does your project have a 'DESCRIPTION' file?
I can copy the server part where the problem appears:
# this makes the directory at the base of your computer.
volumes = c(Home = fs::path_home(), shinyFiles::getVolumes()())
####select the data folder where to read data
shinyFiles::shinyDirChoose(input, 'datafolder', roots = volumes, session = session)
data_path = reactive({
if(length(input$datafolder) != 1 ) {
shinyFiles::parseDirPath(volumes,input$datafolder)
}else{
NULL
}
})
stepb = eventReactive(input$readdatabttn,{
req(data_path(), targets(), analysis())
stepa = list(targets = targets(), analysis = analysis())
withProgress(message = "Reading data...", value=0, {
#external function that takes the path and reads multiple .txt files catching names from the target_file (a .xlsx file)
read_advise_lipidomics(out = stepa, datapath = data_path(), target_file = stepa$targets$targetfile_lipidomics)
})
})
data_path() it's ok because it has the correct path. The problem is when I trigger the eventReactive() with the button input$readdatabttn.
Do you know what is that error? I have the description file and running devtools::check() I have no errors and just a warning:
> checking Rd \usage sections ... WARNING
Undocumented arguments in documentation object 'calibplot_advise_lipidomics'
'plot_calibration'
Undocumented arguments in documentation object 'create_beautiful_radarchart'
'vlabels' 'title' '...'
Undocumented arguments in documentation object 'na_advise_lipidomics'
'na_filter_lip' 'na_filter_sam' 'imputation_met' 'imputation_val'
Undocumented arguments in documentation object 'read_advise_lipidomics'
'datapath'
Undocumented arguments in documentation object 'recovery_advise_lipidomics'
'intercept_flag'
Functions with \usage entries need to have the appropriate \alias
entries, and all their arguments documented.
The \usage entries must correspond to syntactically valid R code.
See chapter 'Writing R documentation files' in the 'Writing R
Extensions' manual.
I solved. The problem was that in the code I take the package version and save it in a variable. I used the function golem::get_golem_version() and this function works only in my dev project directory, in every other project (even on the same computer) doesn't work. For now I write by myself the version, but I would like to automate it.
EDIT:
I used packageVersion() with my package name inside and for now it works.

Batch file oddly looping through subsection of R file

I have a batch file test.bat on my windows desktop with the following content:
cd /d W:\r\dev\
"C:\Program Files\R\R-3.5.0\bin\i386\Rscript.exe" scripts\some_function.R
When executed, the referenced R script some_function.R begins to run and outputs messages to the console to let me know where it is. However, it stops after reaching a certain point in the R code then starts over and continues to do so until the session auto-terminates.
I've inspected the R code for an indication of why the batch file would continue to return to the beginning and I've found none. The R file works fine when run directly (from within R studio, for example).
I'm well aware that naming the batch file with a command that appears in the file can be problematic, but that's not what is happening here. I've tried multiple names for the batch file but that doesn't seem to solve the problem.
Below is the beginning of the code in the referenced file some_function.R that keeps getting re-executed:
library(data.table)
dir <- gsub(x= getwd(), pattern = "(.:/r/)(.*)",replacement = "\\1")
envir <- gsub(x= getwd(), pattern = "(.:/r/)(\\w+)",replacement = "\\2")
cat(paste("directory = "),dir,"\n","environment = ",envir,"\n")
##############################################################
# Load System Parameters #
##############################################################
cat("Loading system parameters ...","\n")
sys_param_file_path <- paste0(dir,"shared/files/system/sys_param.csv")
sys_params <- data.table(read.csv(sys_param_file_path, stringsAsFactors = FALSE))
sys_params <- sys_params[param_envir == envir,]
for(i in 1:nrow(sys_params)){
if(sys_params[i,param_type] == "environment path"){
sys_params[i,param_val := paste(dir,envir,param_val,sep = "")]
}
if(sys_params[i,param_type] == "root path"){
sys_params[i,param_val := paste(substr(dir,1,nchar(dir)-1),param_val,sep = "")]
}
}
cat(paste("Loaded",nrow(sys_params),"parameters","\n"))
and the console output when the batch file is called:
C:\Users\me\Desktop> cd /d W:\r\dev\
W:\r\dev>"C:Program Files\R\R-3.5.0\bin\i386\Rscript.exe" scripts\some_function.R
Warning message:
package 'data.table' was built under R version 3.5.1
directory = W:/r/
environment = dev
Loading system parameters ...
Loaded 32 parameters
directory = W:/r/
environment = dev
Loading system parameters ...
Loaded 32 parameters
directory = W:/r/
environment = dev
Loading system parameters ...
Loaded 32 parameters
What am I missing?

Issue when creating zip file from directory

I have trouble with creating zip file from R. The same code worked perfectly at work with R version 3.4.2, 32 bit computer.
Now I am trying to run the same thing on R version 3.5.1, 64 bit computer, and the zip() command does not seem to work. What is going on?
zip(zipfile = "test.zip",files=list.files(getwd()))
#create zip from whole directory, on 1st machine it works, now nothing happens
I checked the source code for zip() and when I debug it, I found out that system2 command does nothing.
zip <- function (zipfile, files, flags = "-r9X", extras = "", zip = Sys.getenv("R_ZIPCMD",
"zip"))
{
if (missing(flags) && (!is.character(files) || !length(files)))
stop("'files' must a character vector specifying one or more filepaths")
args <- c(flags, shQuote(path.expand(zipfile)), shQuote(files),
extras)
if (.Platform$OS.type == "windows")
invisible(system2(zip, args))
else invisible(system2(zip, args))
}
# I run this manually when trying to debug, nothing happens;
system2(zip, args) ## zip is a parameter here, not a function
####
Browse[2]> zip
[1] "zip"
Browse[2]> args
[1] "-r9X" "\"bla.zip\""
[3] "\"[Content_Types].xml\"" "\"_rels\""
[5] "\"docProps\"" "\"xl\""
[7] ""
For example absurd call does not give an error.
system2("blablađ",2) ## does nothing but no error or warning either
I am stuck trying to understand how does system2() function works and what do I need to change to create a compressed folder.
Thanks
EDIT: After taking the account the help from comment, I got following error:
Browse[2]> system2(zip, args,stderr = T)
Error in system2(zip, args, stderr = T) : '"zip"' not found
SOLVED: After installing Rtools for version 3.5 it worked.
From the zip help:
zip(zipfile, files, flags = "-r9X", extras = "",
zip = Sys.getenv("R_ZIPCMD", "zip"))
zip A character string specifying the external command to be used.
As you can see, the zip function has an argument zip to specify the external command to be used. On my machine it is:
λ where zip
C:\Oracle\Ora11\BIN\zip.exe
C:\Program Files\Rtools\bin\zip.exe
The zip program is available in Rtools, but it is also available on any (Windows?) machine, usually.
To check whether zip is found by R, type:
> Sys.which("zip")
zip
"C:\\Oracle\\Ora11\\bin\\zip.exe"
If you get "", that means zip is not in the path, and if it is neither in the environment variable R_ZIPCMD, you have to specify its path in the zip argument.

How to find correct executable with Sys.which on Windows

What are the workarounds on Windows to make it so Sys.which finds the proper executables? Two cases that are reoccuring problems:
convert.exe which is both a windows program and the ImageMagik program, but Sys.which only finds the windows one which is never wanted from R no matter how I seem to arrange things on my PATH.
tar.exe is packaged along with various things like git or mingw or whatever, and even when I have Rtools and Rbuildtools first in my path, the tar program from Rtools is never found, for example when installing a package from source.
So, I have resorted to writing a wrapper that calls 7-zip instead whenever I am on windows. This can't be the thing to do can it?
Edit
Actually just adding an environment variable to .Renviron: TAR=path/to/tar.exe works fine for the install.packages example, and I am having trouble remembering where else the tar.exe was biting me, but Josh answered the main one, convert.exe.
I asked a +/- identical question earlier this year over on R-devel. Among the replies was this one, by Henrik Bengtsson, who kindly provided the following useful function:
Sys.which2 <- function(cmd) {
stopifnot(length(cmd) == 1)
if (.Platform$OS.type == "windows") {
suppressWarnings({
pathname <- shell(sprintf("where %s 2> NUL", cmd), intern=TRUE)[1]
})
if (!is.na(pathname)) return(setNames(pathname, cmd))
}
Sys.which(cmd)
}
## Trying out Sys.which & Sys.which2 on my Windows box gives the following:
Sys.which("convert")
# convert
# "C:\\Windows\\system32\\convert.exe"
Sys.which2("convert")
# convert
# "C:\\Program Files\\ImageMagick-6.8.8-Q16\\convert.exe"
I'm really not sure why R-core don't just fix Sys.which() to make it actually portable, but they at least do document root cause of this behavior in ?system (whose functionality is afflicted by the same problem):
The search path for 'command' may be system-dependent: it will
include the R 'bin' directory, the working directory and the
Windows system directories before 'PATH'.
Because Sys.which() is vectorized–and since I think that is useful–I've modified the Henrik Bengtsson code in the following function sys_which(), which should be a more robust and more similar version of Sys.which():
## check if unix
is_unix <- function() grepl("unix", .Platform$OS.type, ignore.case = TRUE)
## robust version of Sys.which
sys_which <- function(x) {
if (is_unix()) {
return(Sys.which(x))
}
sys_win <- function(x) {
if (grepl("\\S", path <- Sys.which(x))) {
return(path)
}
path <- tryCatch(
suppressWarnings(system(sprintf("where %s", x), intern = TRUE)[1]),
warning = function(w) "",
error = function(e) "")
if (!grepl("\\S", path)) {
return(`names<-`("", x))
}
`names<-`(path, x)
}
vapply(x, sys_win, character(1))
}
This has the following advantages:
It's vectorized–sys_which() can handle a vector (one or more input values) e.g., sys_which(c("python", "python3"))
It's more error resistant–use of tryCatch(...) ensures any inputs that result in an error from the system call get passed on to the normal Sys.which() function.
Example:
> sys_which(c("python", "python2.7", "python3", "asdf"))
#> python python2.7 python3 asdf
#> "/usr/bin/python" "/usr/bin/python2.7" "/usr/local/bin/python3" ""

Error 43 while knitting a r markdown to pdf on rStudio on Windows

I'm running a rStudio project on the Windows of a colleague (I work on mac, so I'm not in my waters).
When I tried to compile to pdf an .rmd file I get this error:
"C:/Program Files/RStudio/bin/pandoc/pandoc" +RTS -K512m -RTS Plot_per_DPUO.utf8.md --to latex --from markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash-implicit_figures --output "Grafici Professioni/Periodo apr-14 ott-15 test/DH ALLERGOLOGIA - SAN PAOLO.pdf" --template "C:\Users\lucilla.rava\Documents\R\win-library\3.1\rmarkdown\rmd\latex\default.tex" --highlight-style tango --latex-engine pdflatex --variable "geometry:margin=1in"
pandoc.exe: Could not find image `Grafici%20Professioni\Periodo%20apr-14%20ott-15%20test\DH%20ALLERGOLOGIA%20-%20SAN%20PAOLO_files/figure-latex/set-options-1.pdf', skipping...
pandoc.exe: Error producing PDF from TeX source.
! I can't find file `C:/Users/LUCILL'.
<to be read again>
\protect
<*> C:/Users/LUCILL~
1.RAV/AppData/Local/Temp/tex2pdf.3172/input.tex
Please type another input file name
! Emergency stop.
<to be read again>
\protect
<*> C:/Users/LUCILL~
1.RAV/AppData/Local/Temp/tex2pdf.3172/input.tex
! ==> Fatal error occurred, no output PDF file produced!
Transcript written on C:/Users/LUCILL~1.RAV/AppData/Local/Temp/tex2pdf.3172/tex
put.log.
Show Traceback
Rerun with Debug
Error: pandoc document conversion failed with error 43
I left the full paths because I noticed something strange in the user path.
The log prints this snippet:
`C:/Users/LUCILL'.
<to be read again>
\protect
<*> C:/Users/LUCILL~
1.RAV
where the user name is different from how it should be (lucilla.rava).
On mac the compiling doesn't give errors, so the problem shouldn't be in the code.
Of Note: I created the project on my Mac in a folder shared via google drive.
UPDATE 1: Thanks to #Gnusper we noticed that there is a path separator error. Unix and Windows paths are mixed. I need a way to remove the mixing.
In my code I defined the paths with the following code:
months.vec <- get.months(unique(Data$Periodo))
months.vec <- format(months.vec, '%b-%y')
if (type == 1) folder.name <- 'Grafici Generali'
else if (type == 2) folder.name <- 'Grafici Professioni'
else if (type == 3) folder.name <- 'Grafici Indicazioni'
folder.path <- file.path(folder.name, sprintf('Periodo %s %s%s', months.vec[1], tail(months.vec, 1), test))
dir.create(folder.path, recursive = T, showWarnings = F)
for (UO in unique(Data$UO)[1:5]) {
print(file.path(folder.path, sprintf('%s.pdf', sub(pattern = "/", replacement = ' ', UO, fixed = T))))
render('Plot per DPUO.Rmd', clean = T, output_file = file.path(folder.path, sprintf('%s.pdf', sub(pattern = "/", replacement = ' ', UO, fixed = T))))
}
I made some test with a brand new R project on the windows machine with these results:
> file.path('affs', '0sdfsdf')
[1] "affs/0sdfsdf"
> .Platform$file.sep
[1] "/"
>
The path separator is still Unix like. Reading the help of file.path I found this:
file.path(..., fsep = .Platform$file.sep)
[...]
Note
The components are by default separated by / (not ) on Windows.
For some reason the function implements the Unix separator also on windows...
I tried then to run .Platform$file.sep <- '\\'. But when I use file.path() I still get the '/' separator. So fsep = .Platform$file.sep in the arguments it's not evaluated each time the function is run.
In the new project I made more tests:
dir.create(file.path('ssdg','fgsfdg'), recursive = T, showWarnings = F)
write(c(1,2,3,4,5), file = 'ssdg/fgsfdg/test.txt')
write(c(1,2,3,4,5), file = 'ssdg\\fgsfdg\\test2.txt')
write(c(1,2,3,4,5), file = 'ssdg/fgsfdg\\test3.txt')
all of them work and create the file. I also tried dir.create() with various separators combinations and all of them work. Seems like R understand what to do when managing files and correct the separators.
But since the compiling of the .rmd file is performed by pandoc via a shell command, the mix of separators is not fixed and the error occurs.
I find very odd thought that in the error log, pandoc is called with an Unix path
C:/Program Files/RStudio/bin/pandoc/pandoc
How is pandoc able to run and raise the error??
Summing up I need my code to run on both platforms.
UPDATE 2: I tried removing white spaces from every paths in my code. Also I tried to move the scripts and rmd file to a new project in local folder, to check for problems introduced by having a shared project on GoogleDrive.
No improvements whatsoever.
UPDATE 3: I posted the problem as an issue on https://github.com/rstudio/rmarkdown. I implemented the suggestion I was given there (creating the output first in the same folder as the project and then move it to the actual destination folder) but with no luck. however I am pretty sure now that the problem is in the creation and retrieval of the temporary files.
If I run tempdir() on windows it returns:
tempdir()
[1] "C:\\Users\\LUCILL~1.RAV\\AppData\\Local\\Temp\\RtmpUrsOgH"
with the strange shorten user name which is also reported in the error log.
If I run:
normalizePath(tempdir())
[1] "C:\\Users\\lucilla.rava\\AppData\\Loc
I get the correct path.
UPDATE 4:
If it can be useful: I need to set up the path for pdftext every time I open the R project.
In a .Rprofile file I declare:
Sys.setenv(PATH = paste(Sys.getenv("PATH"), "C:\\Program Files\\MiKTeX 2.9\\miktex\\bin\\x64", sep = .Platform$path.sep))
UPDATE 5:
Odd as it seems, we moved to a new windows computer, and the knitting this time worked. No idea why... Nevertheless if someone still has any idea why would be appreciated, since the other computer is the main workstation of my colleague.
Typical Windows Problem. You have "\" in your path, you need to replace it with the "/"
"Grafici Professioni/Periodo apr-14 ott-15 test/DH ALLERGOLOGIA - SAN PAOLO.pdf" --template "C:\Users\lucilla.rava\Documents\R\win-library\3.1\rmarkdown\rmd\latex\default.tex
to
"Grafici Professioni/Periodo apr-14 ott-15 test/DH ALLERGOLOGIA - SAN PAOLO.pdf" --template "C:/Users/lucilla.rava/Documents/R/win-library/3.1/rmarkdown/rmd/latex/default.tex
This determines your OS and loads it one way on Windows and another way everywhere else
if (Sys.info()['sysname'] == Windows) {
"Grafici Professioni/Periodo apr-14 ott-15 test/DH ALLERGOLOGIA - SAN PAOLO.pdf" --template "C:/Users/lucilla.rava/Documents/R/win-library/3.1/rmarkdown/rmd/latex/default.tex"
} else if (Sys.info()['sysname'] == Darwin){
#Mac filepath
} else {
#Linux filepath
}
#gnusper should get credit for finding the slash problem

Resources