【问题标题】:Rscript does not infer inheritance correctlyRscript 不能正确推断继承
【发布时间】:2017-04-27 03:38:35
【问题描述】:

我有这个简单的脚本,其中大部分代码从 Martin Morgan 的this answer 中提取:

#!/usr/bin/Rscript
# sript name: testclass.R
# library(methods)
.A1 <- setClass("A1", representation(a="integer"))
.B1 <- setClass("B1", contains="A1", representation(b="integer"))

A1 <- function(a = integer(), ...) {
    .A1(a=a, ...)
}

B1  <- function(a=integer(), b=integer(), ...) {
    .B1(A1(a), b=b, ...)
}

b <- .B1()

inherits(b, "A1")

如果我用 Rscript 运行脚本,它会产生这个错误:

user@localhost ~/test
  % chmod +x testclass.R                 

user@localhost ~/test
  % ./testclass.R                        
Error: could not find function "setClass"
Execution halted

如果我取消注释 library(methods) 行并再次运行,它会起作用:

user@localhost ~/test
  % ./testclass.R                        
[1] TRUE

或者如果我这样运行,我也不需要手动导入methods

R --vanilla <testclass.R

所以我的问题是,发生了什么,如何避免手动导入 methods 并成功使用 Rscript 运行?

R 版本:

 Rscript --version  
R scripting front-end version 3.3.1 (2016-06-21)
 R --version                                              
R version 3.3.1 (2016-06-21) -- "Bug in Your Hair"
Copyright (C) 2016 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)

更新

作为等待更多信息答案时的解决方法:我可以使用来自littler 包的/usr/bin/r 而不是/usr/bin/Rscript,并且不会发生错误。

【问题讨论】:

  • stat.ethz.ch/R-manual/R-devel/library/utils/html/Rscript.html 表示“Rscript 的默认设置省略了 methods,因为它需要大约 60% 的启动时间。”
  • 在脚本中插入library(method) 有什么缺点?你也可以把它放在你的.Rprofile 文件中,method 将在任何 R 会话中加载。但是,我不鼓励这样做,因为您的脚本不可移植(它们将在其 .Rprofile 中没有 library(method) 的系统上失败)。
  • 您可以将 shebang 更改为 #!/usr/bin/Rscript --default-packages=methods,但正如 @nicola 所提到的,只包含 library(methods) 似乎更简单。
  • @WeihuangWong 缺点是:当人们想要使用Rscript 时,methods 并不是一个明显的依赖关系。当在包中定义类时,我更喜欢包开发中的解决方案。
  • 什么是“包开发解决方案”? Rscript 不导入 method 有据可查,任何人都应该测试他们的代码以查看它是否运行。收到的错误可以立即被检测和纠正,所以不要看看这怎么会是一个问题。

标签: r inheritance rscript


【解决方案1】:

methods 包总是随 R 一起提供,但由于它并不总是需要,Rscript 选择默认不加载它。 ?Rscript 会告诉你这是为了节省启动时间。 Rstudio 和 R 默认加载这个库。如果要在打算使用 Rscript 运行的程序中使用方法包中的函数,那么简单的解决方案是添加以下行:

library(methods)

在脚本中。当通过 Rstudio 或 R 运行时,这并没有什么害处,因为方法包已经在那里加载。我经常将library(methods) 添加到我知道将使用 Rscript 运行的所有脚本中。

【讨论】:

  • 这个是正确答案,不知道为什么OP反对。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-04
  • 2016-11-05
  • 2015-07-04
  • 2021-02-11
  • 2010-09-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多