Error in library(optparse) : there is no package called ‘optparse’ - r

I'm trying to run some demo R code for the optparse package that I got from R-bloggers. I am using ubuntu 14.04
The code is:
#!/usr/bin/env Rscript
library(optparse)
option_list = list( make_option(c("-f", "--file"),
type="character", default=NULL,
help="dataset file name",
metavar="character"),
make_option(c("-o", "--out"),
type="character", default="out.txt",
help="output file name [default=
%default]", metavar="character")
);
opt_parser = OptionParser(option_list=option_list);
opt = parse_args(opt_parser);
if (is.null(opt$file)){
print_help(opt_parser)
stop("At least one argument must be supplied (input file).n",
call.=FALSE)
}
## program...
df = read.table(opt$file, header=TRUE)
num_vars = which(sapply(df, class)=="numeric")
df_out = df[ ,num_vars]
write.table(df_out, file=opt$out, row.names=FALSE)
If the entire script is saved in a file called yasrs.R using the call:
Rscript --vanilla yasrs.R
should return the help messages.
I get an error:
Rscript --vanilla yasrs.R Error in library(optparse) : there is no package called ‘optparse’
I have installed the package (optparse) through RStudio when writing the code and also ensured that it is installed when calling from the terminal. Both terminal and RStudio are running the same R version.
Any suggestions would be appreciated.

Where did RStudio install optparse? Get that from packageDescription("optparse").
Then check the output of .libPaths() in your Rscript environment and your RStudio environment. Maybe RStudio stuck it somewhere that RScript doesn't look.
Then check that even though they may be the same version of R, they might be two different installations. What does R.home() say in each?
One or more of these things will show you why it doesn't find it. Solution is probably to write and run a little RScript that installs it, then you should be fairly sure its going to go in a location that RScript will find it in future.

Related

How can I activate a '.js' script from R?

I have a '.js' script that I usually activate from the terminal using the command node script.js. As this is part of a process where I first do some data analysis in R, I want to avoid the manual step of opening the terminal and typing the command by simply having R do it for me. My goal would be something like this:
...R analysis
write.csv(df, "data.csv")
system('node script.js')
However, when I use that specific code, I get the error:
sh: 1: node: not found
Warning message:
In system("node script.js") : error in running command
Of course, the same command runs without problem if I type it directly on the terminal.
About my Software
I am using:
Linux computer with the PopOS!
RStudio 2021.09.1+372 "Ghost Orchid"
R version 4.0.4.
The error message node: not found indicates that it couldn't find the program node. It's likely in PATH in your terminal's shell, but not in system()'s shell (sh).
In your terminal, locate node by executing which node. This will show the full path to the executable. Use that full path in system() instead.
Alternatively, run echo $PATH in your terminal, and run system('echo $PATH') or Sys.getenv('PATH') in R. Add any missing directories to R's path with Sys.setenv(PATH = <your new path string>)
Note that system2() is recommended over system() nowadays - but for reasons unimportant for your case. See ?system and ?system2 for a comparison.
Examples
Terminal
$ which node
/usr/bin/node
R
system('/usr/bin/node script.js')
# alternatively:
system2('/usr/bin/node', c('script.js'))
or adapt your PATH permanently:
Terminal
% echo $PATH
/usr/local/bin:/home/caspar/programs:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin
R
> Sys.getenv('PATH')
[1] "/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/Applications/RStudio.app/Contents/MacOS/postback"
> Sys.setenv(PATH = "/home/caspar/programs:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/Applications/RStudio.app/Contents/MacOS/postback")

Correct way to use here package with cronR scheduling

I've been using the here package to make my projects more portable. It works great apart from when I use cronR to schedule some of my scripts. When I run my_script.R from Rstudio I get a message from library(here):
here() starts at /home/pd/projects/my_proj
When I set script.R to run using cronR I get a different message:
here() starts at /home/pd
Which is where my_schedule.cron is stored. Ideally I want to keep my_schedule.cron where it is. I can see from the logs that my_script.R runs fine apart from when it comes to saving data because the path used by here() is incorrect. Is there anyway to get the here function to detect the project dir when my_script.R is run from cronR or the terminal?
You can modify the command cmd that is usually created with cron_rscript() by adding cd to your project folder followed by the usual part:
cmd <- "cd /home/pd/projects/my_proj && /usr/lib/R/bin/Rscript ./my_script.R >> ./my_script.log 2>&1"
cron_add(command = cmd, frequency = 'daily', at = '18:00')
If the first line of your #rstats script is wd <- here(), I will come
into your lab and SET YOUR COMPUTER ON FIRE.
Learn how to use environment variables
wd <- Sys.getenv("HOME")
wd <- file.path(wd, "projects", "my_proj")
Or use the 'Additional arguments to Rscript' element in the cronR user interface to pass something extra to the Rscript and fetch it with commandArgs().
If you don't use the cronR interface but cron_rscript, use cronR::cron_rscript(..., rscript_args = "/home/pd/projects/my_proj")
args <- commandArgs(trailingOnly = TRUE)
if(length(args) > 0){
wd <- args[1]
}

Installing packages from binary in R 3.4.0

I recently updated R to the latest release: 3.4.0. R is installed on a network location H:/. Now something weird is happening when I try to install a local binary package:
filename <- paste0("R:/path/independeR_", versions, ".zip")
install.packages(filename,
repos = NULL, type = "source",
lib = gsub("\\\\\\\\networkpath/home/[[:alpha:]]*/",
"H:/", .libPaths()[1]))
Both H:/ and R:/ are network locations. In .libPaths() the default location is in the H:/ location, but it shows with the entire network adress. In the call to install.packages I substituted this.
The code above fails, with the following output:
'\\networkpath\home\JDUB~PN6\DOCU~UZL\R\R-34~TN4.0' is not recognized as an internal or external command,
operable program or batch file.
Warning in install.packages :
running command '"//networkpath/home/JDUB~PN6/DOCU~UZL/R/R-34~TN4.0/bin/x64/R" CMD INSTALL -l "H:\Documents\R\R-3.4.0\library" "R:/path/independeR_0.1.8.zip"' had status 1
Warning in install.packages :
installation of package ‘R:/path/independeR_0.1.8.zip’ had non-zero exit status
There is two things that surprise me here. The directorynames are all jumbled up (DOCU~UZL instead of Documents etc), but for some reason Command promt seems fine with that. The more interesting thing is the following:
When I try to put the command "//networkpath/home/JDUB~PN6/DOCU~UZL/R/R-34~TN4.0/bin/x64/R" CMD INSTALL -l "H:\Documents\R\R-3.4.0\library" "R:/path/independeR_0.1.8.zip" directly into Command Prompt, the output is very similar:
C:\Users\jdubbeldam>"//networkpath/home/JDUB~PN6/DOCU~UZL/R/R-34~TN4.0/b
in/x64/R" CMD INSTALL -l "H:\Documents\R\R-3.4.0\library" "R:/path/independeR_0.1.8.zip"
'\\networkpath\home\JDUB~PN6\DOCU~UZL\R\R-34~TN4.0' is not recognized as
an internal or external command,
operable program or batch file.
For some reason CMD seems to cut off the path to the command halfway through. I guess that this is because the command is too long. When I try the same command, but with H:/Documents/R/R-3.4.0/bin/x64/R, the installation goes just fine.
I would like to be able to automatically install this package from a script, so I would like a solution to this problem from within R. Is there a way to get R to use the shorter H:/Documents/R/R-3.4.0/bin/x64/R?
I was having problems with updating packages, while searching I found that there is a reported bug affecting getting the timestamps from files in Windows 10:
https://bugs.r-project.org/bugzilla3/show_bug.cgi?id=17261
Starting in R 3.4.0, file.info sometimes returns for mtime,
atime and ctime for directories. It seems to have something to do
with sharing. This affects functions that use file.mtime like
update.packages.
Reproduce:
Try file.info() with a random directory. If it returns a legitimate
file time, open a windows explorer window and navigate to the
directory, then run the call again and it will return s.
In some cases it returns s even if the directory is not open (or
in the path of an open explorer window), but this is not consistent.
With a comment of Tomas Kalibera:
Thank you for the report, this is a known bug that has been fixed
recently in R-devel
I found that when I closed the file explorer windows the timestamps worked correctly and didn't show up as NA's.
This may be a lead for why your code isn't working.
I managed to make the following work. However, I think it is extremely ugly, and would still like to see if it is possible to do it someway else.
filename <- paste0("R:/path/independeR_", versions, ".zip")
cmd <- file.path(gsub("//networkpath/home/[[:alnum:]]*/", "H:/",
gsub("//networkpath/home/[[:alnum:]]*~[[:alnum:]]*/",
"H:/", R.home())), "bin/x64/R")
libname <- gsub("\\\\\\\\networkpath/home/[[:alpha:]]*/",
"H:/", .libPaths()[1])
call <- paste(paste0('"', cmd, '"'),
"CMD",
"INSTALL",
"-l",
paste0('"', libname, '"'),
"--no-lock",
paste0('"', filename, '"'),
sep = " ")
system(call)

Run R interactively from Rscript

I'm trying to start a shiny app or an interactive .Rmd document from an Rscript. However, all I get is a message
Listening on http://127.0.0.1:...
I believe this is because R is running in interactive mode (another post about this). How can I write the proper Rscript so that either of the following would work?
My script
#!/usr/bin/Rscript
## This
library(shiny)
runApp(appDir = "../app")
## Or this
## rmarkdown::run("Main.Rmd")
If I understand your question correctly, I was able to achieve this with littler, which I use in lieu of Rscript for scripting tasks that revolve around R. I'm running CentOS 7, and based on the code in your question it looks like you are on a Unix-like machine, so installing littler should not be an issue. For minimal reproducibility, I used the default shiny application and shiny-based Rmarkdown templates provided by RStudio, saving them as testapp (the project / application directory name) and testRMD.rmd, respectively. Then, I have the following scripts:
testapp.r
#!/usr/bin/env r
shiny::runApp(
"~/tmp/delete/testapp",
port = 7088,
launch.browser = TRUE,
host = "127.0.0.1")
testRMD.r
#!/usr/bin/env r
rmarkdown::run(
file = "testRMD.rmd",
dir = "~/tmp/delete",
shiny_args = list(
port = 7088,
launch.browser = TRUE,
host = "127.0.0.1"))
Set the permissions for these files so they can be executed -
[nathan#nrussell R]$ chmod +x testapp.r testRMD.r
(chmod +u ... should suffice, but regardless...), and you should be all set to run them from your terminal, etc...
[nathan#nrussell R]$ ./testapp.r
Loading required package: shiny
Listening on http://127.0.0.1:7088
[nathan#nrussell R]$ ./testRMD.r
Loading required package: shiny
Listening on http://127.0.0.1:7088
There is some additional command line output for the Rmd file that I omitted, but I'm sure this could be suppressed easily if desired. Anyhow, this seems to be working properly - both the shiny application and Rmarkdown application are interactive, just as when launched from RStudio - but if you had something else in mind please clarify.
Thanks #nrussell, your example helped me a lot!
Here is my solution for launching an interactive markdown doc on Windows 10.
REM Change to correct directory
cd "C:\Users\me\Documents\project_folder\"
REM Print files available (not required, but helpful)
dir
REM Point system to R's Pandoc with Rscript then launch
"C:\Program Files\R\R-4.0.3\bin\Rscript.exe" -e ^
"Sys.setenv(RSTUDIO_PANDOC='C:/Users/me/Documents/RStudio/bin/pandoc'); rmarkdown::run(file = 'myInteractiveMarkdown.Rmd', shiny_args = list(launch.browser = TRUE, host = '127.0.0.1'))"
I found I got two errors initially:
When I didn't point the system env to R's pandoc it gave the error message error pandoc version 1.12.3 or higher is required which I solved using the instructions here
When I set the port in the shiny_args, subsequent executions of the bat file would get an error that the port was already busy

How to identify LaTeX errors in .Rd R help files? [duplicate]

When building a package, I received the following warning:
* checking PDF version of manual ... WARNING
LaTeX errors when creating PDF version.
This typically indicates Rd problems.
I have no idea how to even begin diagnosing this. Is there a tool that tells me what .Rd file the problem is in?
I get no warnings about any of my Rd files in the checking documentation step....
Try R CMD Rd2pdf mypackage to create the manual, and possibly also set the --no-clean option to keep the temporary files. This should allow you to debug the LaTeX code triggering the error.
Though #Dirk's answer also helped me to fix the problem I would like to add a bit which might especially help recent updaters. That is, people who haven't encountered other LaTeX / R troubles after the update to 3.1.3 yet. The problem is little bit more general than just building. For me, on OS X the problem was that R CMD Rd2pdf as well as the R CMD CHECK expected texi2dvi to be in /usr/local/bin while it was in /usr/bin.
A symlink helped to fix the problem. On terminal type:
# to check whether the same issue exists for you
which texi2dvi
# if so
cd /usr/local/bin
ln -s /usr/bin/texi2dvi
Of course if the first line returns something else, you need to adapt the symlink here.
Concluding from the comments and from my own experience the problem often seems to be that some TeX fonts are missing, most often
inconsolata.sty and
upquote.sty
First you have to find the right directory where TeX fonts are stored - in my case this is:
C:\Program Files\R\R-3.3.0\share\texmf\tex\latex
Then you can download them here:
https://www.ctan.org/tex-archive/fonts/inconsolata/?lang=en
https://www.ctan.org/tex-archive/macros/latex/contrib/upquote?lang=en
Just copy them to the respective folder and in many cases the problem will be solved (in my case too). This should work for all operating systems.
...and another reason is that you haven't installed MikTex yet.
Download MikTex from here and follow the dialog prompts to install. I found the defaults to be reasonable and worked well for me.
Try to build your R package again. It should be OK now.
In my case, I had no error when running devtools::check() nor devtools::document() but when running R CMD check mypackage_version.tar.gz I got an error:
* checking PDF version of manual ... WARNING
LaTeX errors when creating PDF version.
This typically indicates Rd problems.
LaTeX errors found:
* checking PDF version of manual without hyperrefs or index ... ERROR
In this question in RStudio Community they point to a problem with LATEX installation.
I have the LATEX installation suggested in R markdown cookbook: TinyTex.
I fixed the issue by running in the R console
tinytex::latexmk(file = "../mypackage.Rcheck/mypackage-manual.tex")
This command automatically updated my LATEX installation so the output file mypackage-manual.pdf was created. After this, I did not get any other error related to PDF when running R CMD check:
* checking PDF version of manual ... OK
* DONE
If you are on Ubuntu just install Tex Live by this command:
apt-get install texlive and restart Rstudo if you use it.
First, #dirk-eddelbuettel's approach in the current question identified the missing tex package (which was "makeindex" in my case).
system("R CMD Rd2pdf --no-preview --output=./documentation-peek.pdf ." )
# ... <omitted pages of output> ...
# Warning in sys2(makeindex, shQuote(idxfile)) : '"makeindex"' not found
# Error in texi2dvi(file = file, pdf = TRUE, clean = clean, quiet = quiet, :
# unable to run 'makeindex' on 'Rd2.idx'
# Error in running tools::texi2pdf()
Then #pedro-lima's answer in https://stackoverflow.com/a/69968791/1082435 worked for my specific case.
tinytex::tlmgr_install("makeindex")
Oftentimes this error occur because of Unicode characters in the package. In this cases, the error message might look like this.
See the inputenc package documentation for explanation.
Type H <return> for immediate help.
! Package inputenc Error: Unicode character (U+009D)
(inputenc) not set up for use with LaTeX.
You can find any Unicode characters in your package using tools::showNonASCIIfile(). Here's a simple way to check for these characters in your functions and documentation:
# functions
functions <- list.files(path = './R', all.files = T, recursive = T, full.names = T)
lapply(X=functions, FUN = tools::showNonASCIIfile)
# documentation
docs <- list.files(path = './man', all.files = T, recursive = T, full.names = T)
lapply(X=docs, FUN = tools::showNonASCIIfile)

Resources