How can I activate a '.js' script from R? - 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")

Related

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)

Executing R script within R 3.3.1 installed on windows

Sorry for a basic question. I'm trying run a R script called cuffdiff_gtf_attributes (please find it at enter link description here in R 3.3.1 installed on the Windows 7. The script is started with the below line:
#!/usr/bin/env Rscript
When I type cuffdiff_gtf_attributes in R, it says Error: object 'cuffdiff_gtf_attributes' not found. Also, I tried Rscript cuffdiff_gtf_attributes that returned me: Error: unexpected symbol in "Rscript cuffdiff_gtf_attributes".
Moreover, I tried source('cuffdiff_gtf_attributes.R')that seems to work and returned the usage of the script as bellow
Error:
usage: cuffdiff_gtf_attributes --input=<inputGTF> [--output=outputGTF] | --help
But, when I add the arguments as source('cuffdiff_gtf_attributes.R') --input=file.gtf, it says that: Error: object 'file.gtf' not found. I also tried this command as source('cuffdiff_gtf_attributes.R') --input file.gtf, it says that Error: unexpected symbol in "source('cuffdiff_gtf_attributes.R') --input file.gtf"
Sorry, I couldn't post a sample GTF file, you can find a short sample of it at enter link description here
Everything is the current path. Could you please help me out to execute the script?
Thanks in advance
This is a script file. You should run using Rscript instead for Rgui.exe. From a command prompt, navigate to the directory where file.gtf is and run:
"%Programfiles%\R\R-3.3.3\bin\Rscript" cuffdiff_gtf_attributes.R --input=file.gtf

Calling external program from R with multiple commands in system

I am new to programming and mainly I am able to do some scripts within R, but for my work I need to call an external program. For this program to work on the ubuntu's terminal I have to first use setenv and then execute the program. Googling I've found the system () and Sys.setenv() functions, but unfortunately I can make it function.
This is the code that does work in the ubuntu terminal:
$ export PATH=/home/meme/bin:$PATH
$ mast "/home/meme/meme.txt" "/home/meme/seqs.txt" -o "/home/meme/output" -comp
Where the first two arguments are input files, the -o argument is the output directory and the -comp is another parameter for the program to run.
The reason that I need to do it in R despite it already works in the terminal is because I need to run the program 1000 times with 1000 different files so I want to make a for loop where the input name changes in every loop and then analyze every output in R.
I have already tried to use:
Sys.setenv(PATH="/home/meme/bin"); system(mast "/home/meme/meme.txt" "/home/meme/seqs.txt" -o "/home/meme/output" -comp )
and
system(Sys.setenv(PATH="/home/meme/bin") && mast "/home/meme/meme.txt" "/home/meme/seqs.txt" -o "/home/meme/output" -comp )
but always received:
Error: unexpected constant string in "system(mast "/home/meme/meme.txt""
or
Error: unexpected symbol in "system(Sys.setenv(PATH="/home/meme/bin") && mast "/home/meme/meme.txt""
At this point I have run out of ideas to make this work. If this has already been answered, then my googling have just been poor and I would appreciate any links to its response.
Thank you very much for your time.
Carlos
Additional details:
I use Ubuntu 12.04 64-bits version, RStudio version 0.97.551, R version 3.0.2 (2013-09-25) -- "Frisbee Sailing" Platform: x86_64-pc-linux-gnu (64-bit).
The program I use (MAST) finds a sequence pattern in a list of letters and is part of the MEME SUIT version 4.9.1 found in http://meme.nbcr.net/meme/doc/meme-install.html and run through command line. The command-line usage for mast is:
mast <motif file> <sequence file> [options]
Construct the string you want to execute with paste and feed that to system:
for(i in 1:10){
cmd=paste("export FOO=",i," ; echo \"$FOO\" ",sep='')
system(cmd)
}
Note the use of sep='' to stop paste putting spaces in, and back-quoting quote marks in the string to preserve them.
Test before running by using print(cmd) instead of system(cmd) to make sure you are getting the right command built. Maybe do:
if(TESTING){print(cmd)}else{system(cmd)}
and set TESTING=TRUE or FALSE in R before running.
If you are going to be running more than one shell command per system call, it might be better to put them all in one shell script file and call that instead, passing parameters from R. Something like:
cmd = paste("/home/me/bin/dojob.sh ",i,i+1)
system(cmd)
and then dojob.sh is a shell script that parses the args. You'll need to learn a bit more shell scripting.

Error in untar( ) while using R

I am new to the R programming language and am having basic issues with it. I want to untar a file, but it has not been able to work for me.
Here is the code that I enter:
untar("CD_data.tar", exdir="data")
It then returns the following error message:
/bin/sh: /usr/bin/gnutar: No such file or directory
Warning message:
In untar("CD_data.tar", exdir = "data") :
‘/usr/bin/gnutar -xf 'CD_data.tar' -C 'data'’ returned error code 127
Please help! Thanks!
R on OS X 10.9 (Mavericks) seems to set a wrong TAR environment variable.
You can fix this by adding the following to your .Rprofile (or executing it manually):
Sys.setenv(TAR = '/usr/bin/tar')
Alternatively, you can provide the tar path as an argument when calling untar.
My 2 cents is that you are using a mac and have not installed tar. You are getting value 127 because the command is not found within your $PATH and it's not a built-in command (which is usually the case if you were in unix...
In other words you need to install tar.
Or run it in linux.

R script from command line

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.

Resources