加载并执行R源文件

加载并执行R源文件,r,R,考虑此表单的源文件: # initialize the function f = function() { # ... } # call the function f() 在python中,import函数将加载并执行文件;但是,在R中,source命令会初始化由源文件定义的函数,但是不会调用在文件中调用的函数 是否有任何R命令(或选项)用于导入和执行文件 感谢您的帮助。?源代码说明: Description: ‘source’ causes R to accept its i

考虑此表单的源文件:

# initialize the function
f = function() {
 # ...
}

# call the function
f()
在python中,
import
函数将加载并执行文件;但是,在R中,
source
命令会初始化由源文件定义的函数,但是不会调用在文件中调用的函数

是否有任何R命令(或选项)用于导入和执行文件


感谢您的帮助。

?源代码说明:

Description:

     ‘source’ causes R to accept its input from the named file or URL
     or connection.  Input is read and ‘parse’d from that file until
     the end of the file is reached, then the parsed expressions are
     evaluated sequentially in the chosen environment.
所以,

  • source
    是您正在寻找的函数
  • 我反驳你的说法-
    源代码
    根据文档对我有效
  • 如果您没有看到记录在案的行为,那么一定有另一个问题您没有告诉我们

    您如何推断
    源代码
    没有执行您的
    f

  • 我可以想到一个您可能不知道的场景,它记录在
    ?source
    中,即:

    Details:
    
         Note that running code via ‘source’ differs in a few respects from
         entering it at the R command line.  Since expressions are not
         executed at the top level, auto-printing is not done.  So you will
         need to include explicit ‘print’ calls for things you want to be
         printed (and remember that this includes plotting by ‘lattice’,
         FAQ Q7.22).
    
    未看到按名称调用的对象的输出或未显示基于栅格图形的绘图是自动打印未激活的症状,因为评估未在顶层进行。您需要显式地
    print()
    对象,包括基于栅格的图形,如Lattice和ggplot2图形

    还要注意
    print.eval
    参数,该参数默认为

    > getOption("verbose")
    [1] FALSE
    

    这也可能对您有用。

    该功能也在my system.mine上执行。如果不分配源函数调用的输出,则不会看到它,但分配的变量将在您的工作环境中可用。奇怪--当我在函数中放入print语句时,会调用它,但不会调用qplot函数。但是,当我将文件复制并粘贴到R解释器中时,会调用gplot函数。是否有某种方式可以选择性地调用这些函数或使其静音?注意:eval(parse('filename.R')确实调用gplot.Ah,臭名昭著的ggplot/lattice问题:见@Oliver我在下面的回答中已经解决了这个常见问题。这是由于自动打印未处于活动状态,因为评估未在顶层进行。您需要显式地
    print()
    对象,包括基于栅格的图形,如Lattice和ggplot2图形。