【问题标题】:How to introduce the Shell variable to R script?如何将Shell变量引入R脚本?
【发布时间】:2019-07-06 23:17:11
【问题描述】:

我想在 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 文件。 那么,如何在R脚本中引入Shell变量呢?

【问题讨论】:

  • 这是一个非常常见的任务,有时被称为“R scipt 的命令行参数”或“Rscript 参数解析”。 StackOverflow 上有数百篇文章可供您学习。

标签: r linux shell parameter-passing


【解决方案1】:

这是我通常的做法

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

【讨论】:

  • 你可能也对这个感兴趣stackoverflow.com/a/50654725/786542
  • 它正在连接 Shell 和 R 脚本但无法读取文件 abc.txt。错误 inread.table(args[1], "/results/abc..txt", header = F) : no lines available in input 执行暂停
  • 现在它可以读取 abc.txt 文件,但如果我想再次写入文件,它会失败。文件错误(文件,ifelse(追加,“a”,“w”)):无法打开连接
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-29
  • 1970-01-01
  • 2021-05-21
相关资源
最近更新 更多