我必须使用RStudio创建一个非常简单的R包,其中包含一个函数。
我想把它给一些学生。
加载程序包后,我希望它自动启动我的功能,而无需用户键入其名称。
(该功能等待用户输入或可以打开简单的GUI)
我怎么才能得到它?
PD:我无法修改其他人的.Rprofile,这就是为什么我需要一种在加载包时自动加载函数的方法的原因。
最佳答案
如果您想在R启动时运行某些程序:
启动RStudio,然后运行以下命令在您的主目录中创建.Rprofile
文件:
file.edit("~/.Rprofile")
将以下函数放入该文件:
.First <- function(){
cat("Hello!") # startup message
require(data.table)
# or whatever packages you want to load
# or if you want to run a function in a file
if(file.exists("~/myfile.r")){
source("~/myfile.r")
myfunc()
}
}
保存。做完了!
至于OP的编辑
如果要在加载程序包时运行某些程序,可以使用
.onLoad
和.onAttach
函数。例如:.onAttach <- function(libname, pkgname) {
# to show a startup message
packageStartupMessage("This is my package, enjoy it!")
}
.onLoad <- function(libname, pkgname) {
# something to run
}