系统相关
首页 > 系统相关> > 如何将Shell变量引入R脚本?

如何将Shell变量引入R脚本?

作者:互联网

我想在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.r文件

### 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

标签:shell,parameter-passing,linux,r
来源: https://codeday.me/bug/20191211/2106349.html