Copying files with R Package in Windows - Access is Denied - file.path() - r

I am attempting to fix the slidex package (converts Powerpoint [.pptx] to Xaringan) so it works on Windows. I keep hitting Access is denied errors when this line runs:
file.rename(file.path(basepath, "xml", "ppt", "media"),
file.path(basepath2, "assets", "img"))
Warning message:
In file.rename(file.path(basepath, "xml", "ppt", "media"), file.path(basepath2, :
cannot rename file 'C:\Users\rick2\AppData\Local\Temp\RtmpueUFV7/RCommunityOrg_useR2021/xml/ppt/media' to 'C:\Users\rick2\AppData\Roaming/RCommunityOrg_useR2021/assets/img', reason 'Access is denied'
I see both folders exist and the first has file. file.copy() instead of file.rename() also fails.
Now, I just discovered that adjusting every folder object with code resembling the following solves the problem (borrowed from R Markdown's code),
path <- gsub('/', '\\\\', path)
However, must I do this every time a folder is created with file.path()?
slidex package Github reference (has the file.rename() uses: https://github.com/datalorax/slidex/blob/1c282ee4b71f262605e3ee0bc6d241dac777c5ea/R/utils.R
Per #Parfait, adding:
In the aforementioned utils.R one sees:
dir.create(file.path(basepath, "assets"), showWarnings = FALSE)
dir.create(file.path(basepath, "assets", "img"), showWarnings = FALSE)
file.rename(file.path(basepath, "xml", "ppt", "media"),
file.path(basepath, "assets", "img"))
basepath is the following without the slash-conversion I added to try and eliminate the error:
"C:/Users/rick2/AppData/Local/Temp/RtmpOCoUB3/RCommunityOrg_useR2021"
file.rename() attempts to rename the first to the second here, and file. copy() also fails:
file.path(basepath, "xml", "ppt", "media")
"C:/Users/rick2/AppData/Local/Temp/RtmpOCoUB3/RCommunityOrg_useR2021/xml/ppt/media"
file.path(basepath, "assets", "img")
"C:/Users/rick2/AppData/Local/Temp/RtmpOCoUB3/RCommunityOrg_useR2021/assets/img"
I just discovered that my solution failed to copy the files so I will accordingly edit the above later.

Related

Why does dir.create give cannot create dir 'results', reason 'No such file or directory'?

After run my analysis I tried to create a new folder and save my results. I got the message:
dir.create("results")
Warning message:
In dir.create("results") :
cannot create dir 'results', reason 'No such file or directory'
In case you want to create a new nested directory, e.g. "D:/mytest/myresults", wehre D:/mytest needs to be created as well as the subdirectory /myresults, dir.create() will not work when you use:
dir.create("D:/mytest/myresults")
Becasue "D:/mytest" does not exist, you cannot create "D:/mytest/myresults" and you will receive the warning:
In dir.create("D:/mytest/myresults") : cannot create dir
'D:\mytest\myresults', reason 'No such file or directory'
Use recursive = TRUE insted:
dir.create("D:/mytest/myresults", recursive = TRUE)
Using recursive = TRUE is equivalent to creating the base directory first and the subdirectory after that, like:
dir.create("D:/mytest")
dir.create("D:/mytest/myresults")

R Script .bat file - Adding Source before executing

I have an 'R' file which inserts reads data from a database, does some calculations, then re-inserts data back into a table.
Before i execute the script, I run 'Source' as below..
I want to use Windows Task Scheduler to auto schedule this script to run. I am following the guide https://trinkerrstuff.wordpress.com/2015/02/11/scheduling-r-tasks-via-windows-task-scheduler/ - When creating the .BAT file it should look something like:
echo off
CMD BATCH C:\PATHNAME\RSCRIPT.R
What should i insert here to make sure it runs the 'Source' first?
In the R code i have
In the code i have:
#use a relative path to locate our common utilities file and source it
source("..//R-Utilities//Utilities.R")
# use check_install_package function from Utilities.R to install and load
packages
check_install_package("lubridate")
check_install_package("plyr")
check_install_package("dplyr")
check_install_package("dtplyr")
check_install_package("ISOweek")
check_install_package("stringi")
check_install_package("RODBC")
#give us access to the library of functions this script uses
source("CTB_functions.R")
But I need to click the source button before running my whole code, or i get an error (As below).
> #this automatically sets the working directory to be where this file is
> setwd(getSrcDirectory(function(x) {x}))
Error in setwd(getSrcDirectory(function(x) { :
cannot change working directory
>
> #use a relative path to locate our common utilities file and source it
> source("../R-Utilities/Utilities.R")
Error in file(filename, "r", encoding = encoding) :
cannot open the connection
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
cannot open file '../R-Utilities/Utilities.R': No such file or directory
>
> # use check_install_package function from Utilities.R to install and load
packages
> check_install_package("lubridate")
Error: could not find function "check_install_package"
> check_install_package("plyr")
Error: could not find function "check_install_package"
> check_install_package("dplyr")
Error: could not find function "check_install_package"
> check_install_package("dtplyr")
Error: could not find function "check_install_package"
> check_install_package("ISOweek")
Error: could not find function "check_install_package"
> check_install_package("stringi")
Error: could not find function "check_install_package"
> check_install_package("RODBC")
Error: could not find function "check_install_package"
>
> #give us access to the library of functions this script uses
> source("CTB_functions.R")
Error in file(filename, "r", encoding = encoding) :
cannot open the connection
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
cannot open file 'CTB_functions.R': No such file or directory
Given your script, there should be no need to click the “Source” button first: in fact, it would execute your script twice.
A few things about your scripts:
CMD BATCH C:\PATHNAME\RSCRIPT.R
This is missing R in front of CMD BATCH. However, You should probably use Rscript.exe instead of R CMD BATCH. It’s a modern replacement.
source("..//R-Utilities//Utilities.R")
There’s no need for double slashes: single slashes work.
source("../R-Utilities/Utilities.R")
More fundamentally, using source in this manner can quickly become complex and error-prone due to several shortcomings (e.g circular inclusion, relative paths etc). A better way of achieving this is via the ‘box’ package, which provides a vastly improved replacement for the source function, which seems to fit your use-case very closely.
In particular, your script will probably not work: source won’t find the files R-Utilities/Utilities.R and CTB_functions.R because it searches these relative to the current working directory, not relative to the script directory. Using ‘box’ fixes this.

How to fix "Unable to find GhostScript executable to run checks on size reduction" error upon package check in 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

path error for tree tagger with koRpus R package

I try to use treeTagger that I installed from here in R with the package koRpus.
library(koRpus)
tagged.results <- treetag(as.factor("salut ça va"), treetagger="manual", lang="fr", TT.options=list(path="C:\\TreeTagger\\bin\\tree-tagger.exe"))
generates the following error :
Erreur dans path.expand(path) : argument 'path' incorrect
Which I don't understand because I can see all the files in this path, which are : tree-tagger and tree-tagger-flush (application files), tag-french and chunk-french which are windows command file.
I also tried :
set.kRp.env(TT.cmd="C:\\TreeTagger\\bin\\tree-tagger.exe", lang="fr")
tagged.text <- treetag(as.factor("salut ça va"),lang="fr")
The second generates the same error
There are several issues here. First the as.factor("salut ca va") should be a file with that text in it. You are also missing a preset value inside of TT.options. You will want to put preset="fr" after the path argument. Finally the path itself should point to the root directory.
The documentation here states "TT.options
A list of options to configure how TreeTagger is called. You have two basic choices: Either you choose one of the pre-defined presets or you give a full set of valid options:
path Mandatory: The absolute path to the TreeTagger root directory. That is where its subfolders bin, cmd and lib are located."
You are pointing the path variable inside of the bin directory to the .exe file. Run the following code to point to the root directory where the bin directory is located as follows:
library(koRpus)
tagged.results <- treetag("test.txt", treetagger="manual", lang="fr", TT.options=list(path="C:\\TreeTagger", preset="fr"))

Accessing "examples" subdirectory in R-package

I using a CRAN package which contains a subdirectory "examples/" containing a file "ex.txt". How do I access this file?
I tried
require("XX")
read.table(paste(.path.package("XX"), "/examples/ex.txt", sep=""), header=TRUE, sep="\t")
but then the file is not found. When I look in the installation directory of the package, I indeed see no "examples/" subdirectory. However, when I run R CMD check and R CMD INSTALL on the package source, I get no warnings about the "examples/" subdirectory. So the package installs without problems, but omits the examples. What do I have to do in order to access the files in "examples/"?
At first I misread your question and thought you were the package author. The problem is that as you noticed examples doesn't get copied in when installed. A solution would be for the package authors to put the folder in /inst/examples instead of /examples. Since you don't have control of that we can create a workaround by downloading the source and then using that instead.
# Downloads the source code for a package
# Extracts it to a temporary directory
downloadAndExtract <- function(package, tdir = tempdir()){
down <- download.packages(package, destdir = tdir)
targz <- down[,2]
untar(targz, exdir = tdir)
file.path(tdir, package)
}
path <- downloadAndExtract("XX")
filepath <- file.path(path, "examples", "ex.txt")
dat <- read.table(filepath, header = TRUE, sep = "\t")
Clearly this isn't ideal but since you won't find that file in the installed package we need to resort to some sort of workaround...

Resources