R script from command line - r

I wanted to run this example script: http://mazamascience.com/WorkingWithData/?p=912 from Windows command line. So I opened the command line and typed Rscript tryCatch.R 1. However, I keep getting the error message Error: R not found. I did set the PATH environment variable as C:\Programme\R\R-3.0.1\bin. If I just type R.exe, it does start R, but it cannot find the packages that are to be loaded at start (e.g. package 'utils' in options<"defaultPackages"> was not found). I guess I have to set another path to the libraries somewhere, but I haven't got any idea where to do this.
UPDATE: After explicitly typing PATH C:\Programme\R\R-3.0.1\bin (rather than just adding this to the value of the environment variable PATH) it seems that R is found. However, a new problem occurs: In normalizePath<path.expand(path), winslash, mustWork>: path[2] = "C:/Programme/R/R-3.0.1/library": Access denied, the same than for the methods library. Then: Calls: .First ... library -> .getRequiredPackages2 -> library -> normalizePath Execution stopped. I'm using Windows 7 and I do have administrator rights.

Rscript is very handy (R CMD BATCH is the old way to ) specially under windows, But generally under I create a batch file to avoid all path's headache.
For example say launcher.bat:
#echo off
C:
PATH C:\Programme\R\R-3.0.1\bin;%path%
cd PATH_TO_YOUR_RSCRIPT
Rscript tryCatch.R 1
pause
And open a console(using cmd) , go where you have stored your launcher.bat and launch it. Or from the R cosnole using shell:
shell('path_to_launcher\launcher.bat')

I've found out that it was a language-specific problem on Windows 7, similar to what is described here: https://stat.ethz.ch/pipermail/r-help/2011-May/276932.html
After changing PATH to C:\Program Files\R\R-3.0.1\bin the script is properly executed from the command prompt.
Thanks to everyone who tried to help!

I ran into this problem under windows 7, apparently, when setting environment variables>user variables the path is not added into the PATH, so the user must add this path in system variables > PATH
at the end just add the path to your .EXE files and voila.

Related

Error with install.packages using renv|knit|rmarkdown

I'm updating the renv folder from a project in order to adjust the libraries, but it seems I'm having a permission problem. After running renv::init() and trying to installing manually the remaining libraries using install.packages() I always get the message
Error: failed to retrieve 'https://cran.rstudio.com/bin/windows/contrib/4.2/ipeadatar_0.1.6.zip' [error code 23]
1: curl: (23) Failure writing output to destination
2: curl: (23) Failure writing output to destination
Using .libPath() I can see that the renv was created in the "AppData" hidden folder
1] "C:/Users/André Ferreira/AppData/Local/R/cache/R/renv/library/MacroBRA_Wrld-09789847/R-4.2/x86_64-w64-mingw32"
So checking my permissions, I couldn't see anything wrong. Any thoughts about this problem? The thing it's that when I open my .Rmd file and try to knit, I receive the same message "1: curl: (23) Failure writing output to destination", now from rmarkdown retrieve installation, so it may be a configuration/permission problem.
Adding "C:\rtools42\usr\bin" and "C:\Program Files\R\R-4.2.1\bin" in the environment variable didn't help.
As I could see, opening an empty file from rstudio, I could use install.packages() without problem.
Although this doesn't solve the problem directly, you can also instruct renv to use a different library path with something like:
# use a project-local library path
RENV_PATHS_LIBRARY = renv/library
in your project's .Renviron file. Depending on your environment, you might also consider placing the library path in an alternate location.
See https://rstudio.github.io/renv/articles/packages.html#r-cmd-build-and-the-project-library for more details.

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")

How to add context menu option to start a program in the given working directory

When you install Git on windows, it adds a context menu option when you right-click on a folder to "Git Bash Here". The way it does this is by adding a registry key like this:
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\Directory\shell\git_shell\command]
#="\"C:\\Program Files\\Git\\git-bash.exe\" \"--cd=%1\""
Notice the cd argument at the end that passes the directory name to the program.
I would like to do something similar for R (and other programs). Unfortunately R doesn't accept a cd argument. This will launch R:
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\Directory\shell\R\command]
#="\"C:\\Program Files\\R\\R-3.4.3\\bin\\x64\\Rgui.exe\" \"--cd=%1\""
but it gives an error message saying the cd argument is not recognized, and Rgui will start with whatever the default working directory is, defeating the entire point.
What I really want it to do is the equivalent of this command:
start "R" /D %1 "C:\Program Files\R\R-3.4.3\bin\x64\Rgui.exe"
where %1 is the folder that was right-clicked on. Is this possible?
You can write R code that runs on startup and checks the commandline arguments.
You can put the following code at the end of C:\Program Files\R\R-3.4.3\etc\Rprofile.site (or any other file that gets executed at startup):
local({
processArg <- function(arg) {
parts <- strsplit(arg, "=")[[1]]
if (length(parts) == 2) {
if (parts[1] == "R_startup_wd") {
setwd(parts[2])
}
}
}
invisible(sapply(commandArgs(FALSE), processArg))
})
It checks if R was called with an argument R_startup_wd=your_working_dir and changes the working directory if yes.
You can then call R like
"C:\Program Files\R\R-3.4.3\bin\x64\Rgui.exe" "R_startup_wd=your_working_dir"
Note that the argument name is given without "--", i.e. we have R_startup_wd and not --R_startup_wd. Otherwise RGui will complain about "unknown arguments"
You can of course still use R without the argument given.

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)

R system functions always returns error 127

I need to execute an external tool from R and process errors (if any) occurred in that tool.
I know 3 functions to do something familiar with my task:
shell, system and system2.
Trying to test those, I see that command
shell("notepad")
opens notepad. As far as I know shell doesn't allow to check errors (there's no interface to look into stderr).
When I call
system("notepad")
or
system2("notepad")
R freezes trying to make those commands.
Calling
system("start notepad")
or
system2("start notepad")
returns warning
Warning message:
running command '"start notepad"' had status 127
Adapting #DavidTseng's answer (sorry for not having enough reputation to upvote it)...
system("cmd.exe", input = "notepad")
worked for me in Windows.
As I mentioned in my comments, the R documentation reveals that in Windows the system() function does not launch a separate shell (if needed). This is why command line commands run with system(), but Notepad, which needs a separate window, does not run:
From the documentation for system():
The most important difference is that on a Unix-alike system launches a shell which then runs command. On Windows the command is run directly – use shell for an interface which runs command via a shell (by default the Windows shell cmd.exe, which has many differences from a POSIX shell).
system("bash -l", input = "notepad")
I'm not sure if there's been an update to R that allows this since the question was asked nearly four years ago, but system("\"C:\path\to\exe.exe\" args", intern = T) works for me and WILL bring up a separate child window and works on Windows 10 + R 3.6 + RStudio.
Not using the 'intern = T' was giving me a return code of 127 and did not run the process.
I had the same issue. there is an additional step in the installation process which i did not do.
refer to to the url
https://cran.r-project.org/bin/windows/Rtools/
Look for "Putting Rtools on the PATH"
writeLines('PATH="${RTOOLS40_HOME}\usr\bin;${PATH}"', con = "~/.Renviron")
for windows users
wrong: system(path("c:", "program files", "r", "anysoft.EXE"))
but works : system(path("c:", shQuote("program files"), "r", "anysoft.EXE"))
You guys are making it so complicated. I solved this problem by referring to this answer. The problem is with the PATH. type Sys.which('') in R, and you will see nothing. So you have to set the path in CMD, and then use Sys.setenv(PATH = '') in R to get this work.

Resources