我想在Shell脚本中运行一个R脚本,这对我来说不是问题:
例:
#!/bin/bash
_input_file=$1
_output_file=$2
some shell script...
........
Rscript R.r >"_output_file" #call R script
我的问题是我想在我的Shell脚本中定义一个变量(_output_file)来分配给我的R脚本。 _output_file包含输出的路径和文件夹名称。
R脚本:
#!/usr/bin/env Rscript
x <- read.csv(_output_file,"/results/abc.txt", header=F)
library(plyr)
.....
.........
所以我希望调用变量(_output_file)及其路径能够读取abc.txt文件。那么,如何将Shell变量引入R脚本?
这就是我通常这样做的方式
Shell脚本文件
#!/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. fil fillet
### 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