Reputation: 107
I'd like to run a R Script within a Shell Script, which is not a problem to me:
Example:
#!/bin/bash
_input_file=$1
_output_file=$2
some shell script...
........
Rscript R.r >"_output_file" #call R script
My Problem is I'd like to define a variable (_output_file) within my Shell Script to assign to my R Script. _output_file contain path and folder name of output.
R script :
#!/usr/bin/env Rscript
x <- read.csv(_output_file,"/results/abc.txt", header=F)
library(plyr)
.....
.........
So I would like the call variable (_output_file) and its path to be able to read abc.txt file. So,how to introduce the Shell variable to R script?
Upvotes: 4
Views: 2271
Reputation: 28441
This is how I usually do it
Shell script file
#!/bin/bash
_input_file=$1
_output_file=$2
# preprocessing steps
# run R.r script with ${_output_file} parameter
Rscript --vanilla R.r ${_output_file}
echo
echo "----- DONE -----"
echo
exit 0
R.r file
### Ref links
# http://tuxette.nathalievilla.org/?p=1696
# https://swcarpentry.github.io/r-novice-inflammation/05-cmdline/
# get the input passed from the shell script
args <- commandArgs(trailingOnly = TRUE)
str(args)
cat(args, sep = "\n")
# test if there is at least one argument: if not, return an error
if (length(args) == 0) {
stop("At least one argument must be supplied (input file).\n", call. = FALSE)
} else {
print(paste0("Arg input: ", args[1]))
}
# use shell input
file_to_read <- paste0(args[1], "/results/abc.txt")
print(paste0("Input file: ", file_to_read))
df <- read.csv(file_to_read, header = F)
# check
head(df)
summary(df)
library(plyr)
# do something here
Upvotes: 3