如何在不退出R的情况下从终端执行R单行



这个问题及其答案展示了如何从终端打开R,评估您想要的表达式,然后退出R,所有这些都在一行中完成。最干净的答案是打开您的终端,然后运行R --slave -e 'EXPR',其中EXPR是您的表达式(例如R --slave -e '1+1'(。

我的问题是:如何在不退出R的情况下完成所有这些?也就是说,我想在我的终端中的一行中输入R并计算我想要的表达式;明显的";像R '1+1'R 1+1这样的答案不起作用,返回错误ARGUMENT '1+1' __ignored__,而像R; 1+1这样的Bash滥用拒绝评估第二个表达式,直到R关闭。

使用一个函数,您可以在使用以下参数后自动重新启动R:

r() {
# First execute commands when given
if [ $# -gt 0 ]; then
R --slave -e "$*"
fi
# Start R 
R --slave
}    

测试后,您可以将此功能添加到.bashrc
我调用函数r,但请确保您的系统尚未使用或保留r
可以使用r 1+1r 1 + 1r "1*2"调用函数
使用"1*2"时,请注意引号。如果没有引号,shell将尝试扩展特殊字符,并将查找文件";1*2";。如果有空格,情况会更糟,r 1 * 2将用很多文件名替换*

扩展@ekoam的建议很容易让我们找到你想要的东西,我认为:

# just place this in your .bashrc or .zshrc, etc.
R_expr() {
# will overwrite your Rprofile each time so use with care.
echo $1 > .Rprofile 
exec R
}

现在,只要你想,就可以使用你新创建的实用程序R_expr

jkix $ R_expr "1+1" 
----------------------------------------------------------------
R version 4.0.2 (2020-06-22) -- "Taking Off Again"
Copyright (C) 2020 The R Foundation for Statistical Computing
Platform: x86_64-apple-darwin17.0 (64-bit)
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.
Natural language support but running in an English locale
R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.
Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.
[1] 2
[Previously saved workspace restored]
> print("We did it! We're still in R!")

这也是非常可定制的:也许你有一个想要运行的脚本,而不仅仅是一个表达式:

R_script() {
cat $1 > .Rprofile # in this case, the first argument is a script
exec R 
}
# then...
R_script some_script.R # followed by any options you want

这两种解决方案的好处是,传入的代码在运行时执行,并且定义的任何变量等都将可用于新的交互式会话。另外,请注意,您仍然可以将命令行参数传递给R:

CCD_ 18。

希望这有帮助!

新答案:

创建一个名为CCD_ 19的脚本,其中包含CCD_;然后在终端CCD_ 21中运行返回:

tester@LAPTOP MINGW64 ~/Documents
$ Rscript oneplusone.R
[1] 2

旧答案:

在我的情况下(我正在运行windows(,我会做以下操作:

  1. 打开CMD
  2. 将目录更改为R文件夹
  3. 运行R.exe
  4. 运行任何代码

因此在CMD:中

cd "C:Program FilesRR-4.0.3bin"
R.exe
> 1+1
[1] 2

编辑:对于Linux,请查看:http://www.cureffi.org/2014/01/15/running-r-batch-mode-linux/

最新更新