在R中创建用户创建的函数

时间:2022-11-18 22:01:44

I'm sorry if this has been asked before but I can't find the answer.

如果以前曾经问过我,我很抱歉,但我找不到答案。

Let's say I write a small function in R

假设我在R中写了一个小函数

add2<-function(a){
return(a+2)
}

I save it as add2.R in my home directory (or any directory). How do I get R to find it??

我将它保存为我的主目录(或任何目录)中的add2.R。我如何让R找到它?

> add2(4)
Error: could not find function "add2"

I know I can open up the script, copy/paste it in the console, run it, and then it works. But how do I get it built-in so if I open and close R, it still runs without me copying and pasting it in?

我知道我可以打开脚本,将其复制/粘贴到控制台中,运行它,然后就可以了。但是如何让它内置,所以如果我打开和关闭R,它仍然在没有我复制并粘贴它的情况下运行?

3 个解决方案

#1


17  

One lightweight option:

一个轻量级选项:

dump("add2", file="myFunction.R")

## Then in a subsequent R session
source("myFunction.R")

An alternative:

替代:

save("add2", file="myFunction.Rdata")

## Then just double click on "myFunction.Rdata" to open  
## an R session with add2() already in it 

## You can also import the function to any other R session with
load("myFunction.Rdata")

Until you're ready to package up functions into your own private package, storing them in well organized, source()-ready text files (as in the 1st example above) is probably the best strategy. See this highly up-voted SO question for some examples of how experienced useRs put this approach into practice.

在您准备将函数打包到您自己的私有包之前,将它们存储在组织良好的源()就绪文本文件中(如上面的第一个示例中)可能是最好的策略。有关经验丰富的用户如何将此方法付诸实践的一些示例,请参阅此高度投票的SO问题。

#2


4  

Before invoking the function (e.g. at the beginning of the script), you should source the file containing your user defined function/s, i.e. :

在调用函数之前(例如在脚本的开头),您应该获取包含用户定义函数的文件,即:

source("add2.R") # this executes add2.R script loading add2 function

Basically, source function executes the code included in the script passed as argument. So if the file contains only functions definitions it loads the function in memory for future use.

基本上,源函数执行作为参数传递的脚本中包含的代码。因此,如果文件仅包含函数定义,则会将该函数加载到内存中以供将来使用。

#3


4  

If you want to start it automatically, then you have to set-up startup script and then use one of the methods outlined in answers above.

如果要自动启动它,则必须设置启动脚本,然后使用上面答案中列出的方法之一。

/Library/Frameworks/R.framework/Versions/2.15/Resources/etc/ is(for mac) the location of Rprofile.site, which must be edited adequately.

/Library/Frameworks/R.framework/Versions/2.15/Resources/etc/是(对于mac)Rprofile.site的位置,必须对其进行充分编辑。

My version of it is:

我的版本是:

.First <- function()
{ 
    dir='~/Desktop/Infobase/R/0_init/0_init.R'
    if(file.exists(dir))
    {
    source(dir, chdir = TRUE) 
    } else {cat("startup file is not found at:",dir)}
    cat("\nWelcome at", date(), "\n")
}    

.Last <- function()
{ 
cat("\nGoodbye at ", date(), "\n")
}

Note, that after you have sourced 1 R script, you do not need to enter this file anymore. Just do all you need from the file you sourced. In my case file "0_init.R" contains no functions, it just contains loading of other scripts. Well, you've got the idea.

请注意,在您获得1 R脚本之后,您不再需要输入此文件。只需从您采购的文件中完成所需操作即可。在我的情况下,文件“0_init.R”不包含任何函数,它只包含其他脚本的加载。嗯,你有这个想法。

Also, if you are doing this I recommend you to store them in new environment. Actual environments are not really suitable for your own functions(They are better implemented if you have a package developed, otherwise you lose a lot of control).

此外,如果您这样做,我建议您将它们存储在新环境中。实际环境并不适合您自己的功能(如果您开发了一个包,它们会更好地实现,否则您将失去很多控制权)。

use "attach", "detach", "search", etc....

使用“附加”,“分离”,“搜索”等....

attach(FUN,name="af2tr")

#1


17  

One lightweight option:

一个轻量级选项:

dump("add2", file="myFunction.R")

## Then in a subsequent R session
source("myFunction.R")

An alternative:

替代:

save("add2", file="myFunction.Rdata")

## Then just double click on "myFunction.Rdata" to open  
## an R session with add2() already in it 

## You can also import the function to any other R session with
load("myFunction.Rdata")

Until you're ready to package up functions into your own private package, storing them in well organized, source()-ready text files (as in the 1st example above) is probably the best strategy. See this highly up-voted SO question for some examples of how experienced useRs put this approach into practice.

在您准备将函数打包到您自己的私有包之前,将它们存储在组织良好的源()就绪文本文件中(如上面的第一个示例中)可能是最好的策略。有关经验丰富的用户如何将此方法付诸实践的一些示例,请参阅此高度投票的SO问题。

#2


4  

Before invoking the function (e.g. at the beginning of the script), you should source the file containing your user defined function/s, i.e. :

在调用函数之前(例如在脚本的开头),您应该获取包含用户定义函数的文件,即:

source("add2.R") # this executes add2.R script loading add2 function

Basically, source function executes the code included in the script passed as argument. So if the file contains only functions definitions it loads the function in memory for future use.

基本上,源函数执行作为参数传递的脚本中包含的代码。因此,如果文件仅包含函数定义,则会将该函数加载到内存中以供将来使用。

#3


4  

If you want to start it automatically, then you have to set-up startup script and then use one of the methods outlined in answers above.

如果要自动启动它,则必须设置启动脚本,然后使用上面答案中列出的方法之一。

/Library/Frameworks/R.framework/Versions/2.15/Resources/etc/ is(for mac) the location of Rprofile.site, which must be edited adequately.

/Library/Frameworks/R.framework/Versions/2.15/Resources/etc/是(对于mac)Rprofile.site的位置,必须对其进行充分编辑。

My version of it is:

我的版本是:

.First <- function()
{ 
    dir='~/Desktop/Infobase/R/0_init/0_init.R'
    if(file.exists(dir))
    {
    source(dir, chdir = TRUE) 
    } else {cat("startup file is not found at:",dir)}
    cat("\nWelcome at", date(), "\n")
}    

.Last <- function()
{ 
cat("\nGoodbye at ", date(), "\n")
}

Note, that after you have sourced 1 R script, you do not need to enter this file anymore. Just do all you need from the file you sourced. In my case file "0_init.R" contains no functions, it just contains loading of other scripts. Well, you've got the idea.

请注意,在您获得1 R脚本之后,您不再需要输入此文件。只需从您采购的文件中完成所需操作即可。在我的情况下,文件“0_init.R”不包含任何函数,它只包含其他脚本的加载。嗯,你有这个想法。

Also, if you are doing this I recommend you to store them in new environment. Actual environments are not really suitable for your own functions(They are better implemented if you have a package developed, otherwise you lose a lot of control).

此外,如果您这样做,我建议您将它们存储在新环境中。实际环境并不适合您自己的功能(如果您开发了一个包,它们会更好地实现,否则您将失去很多控制权)。

use "attach", "detach", "search", etc....

使用“附加”,“分离”,“搜索”等....

attach(FUN,name="af2tr")