R语言命令行执行代码的3种方式(传递参数和环境变量)

您所在的位置:网站首页 r语言界面怎么用 R语言命令行执行代码的3种方式(传递参数和环境变量)

R语言命令行执行代码的3种方式(传递参数和环境变量)

#R语言命令行执行代码的3种方式(传递参数和环境变量)| 来源: 网络整理| 查看: 265

R语言命令行执行代码的3种方式(传递参数和环境变量) 使用R使用Rscript使用R CMD BATCH

大部分情况在IDE环境中运行R程序,但有时也需要在shell中运行,和其他语言的脚本一样。在shell中如何运行R语言的代码呢?

为了简化使用,把R/Rscript的可执行路径加入path环境变量。(bash,windows cmd)

使用R

首先看看R的help

c:\R> R --arch x64 --help Usage: Rterm [options] [< infile] [> outfile] [EnvVars] Start R, a system for statistical computation and graphics, with the specified options EnvVars: Environmental variables can be set by NAME=value strings Options: -h, --help Print usage message and exit --version Print version info and exit --encoding=enc Specify encoding to be used for stdin --encoding enc ditto --save Do save workspace at the end of the session --no-save Don't save it --no-environ Don't read the site and user environment files --no-site-file Don't read the site-wide Rprofile --no-init-file Don't read the .Rprofile or ~/.Rprofile files --restore Do restore previously saved objects at startup --no-restore-data Don't restore previously saved objects --no-restore-history Don't restore the R history file --no-restore Don't restore anything --workspace=file Workspace to be restored --vanilla Combine --no-save, --no-restore, --no-site-file, --no-init-file and --no-environ --max-mem-size=N Set limit for memory to be used by R --max-ppsize=N Set max size of protect stack to N -q, --quiet Don't print startup message --silent Same as --quiet --no-echo Make R run as quietly as possible --verbose Print more information about progress --args Skip the rest of the command line --ess Don't use getline for command-line editing and assert interactive use -f file Take input from 'file' --file=file ditto -e expression Use 'expression' as input One or more -e options can be used, but not together with -f or --file An argument ending in .RData (in any case) is taken as the path to the workspace to be restored (and implies --restore)

由此可见,R可以接受输入重定向的文件内容,可以通过-f file或--file=file指定文件输入。

有一个选项--args可以提示R跳过之后的参数,其实后面的参数作为传递给R进程。脚本中的 commandArgs()函数可以捕获命令行输入的所有参数。其中,trailingOnly = TRUE只获得–args之后的参数。

命令行还可以定义NAME=value形式的环境变量。环境变量的设置和--agrs无关。

举个栗子: (简单起见,增加--vanilla --no-echo参数) demo.R内容

cat("\n") cat("commandArgs(trailingOnly = FALSE)\n") (args1


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3