我将一个函数放入我的.Rprofile文件中,但是当我加载R时它没有出现?我不明白为什么

时间:2014-12-11 11:27:02

标签: r

我的.Rprofile文件如下所示:

# Will be run at the start of an R sesssion
# -----------------------------------------
.First <- function(){
    # Set the default CRAN
    CRAN <- "http://cran.ma.imperial.ac.uk/"
    # Load standard libraries
    library(Hmisc)




    # My functions
    # ------------
    # R version of lookfor: `names(data)[grep('pattern',names(data))]`

    lkf <- function(d,p) names(d)[grep(p,names(d))]
    cat("\nWelcome at", date(), "\n")

}

# Will be run at the end of an R sesssion
# -----------------------------------------

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

我使用lkf函数快速查找特定数据框中的变量。它以Stata lookfor函数为模型。但是,当我开始使用R时,我无法使用它。

e.g。

> ls()
[1] "fresh_install"
> mydata <- data.frame(id = c(1:10))
> ls()
[1] "fresh_install" "mydata"
> lkf(mydata,"id")
Error: could not find function "lkf"

我做错了什么?

1 个答案:

答案 0 :(得分:1)

来自?Startup

  

接下来,如果在搜索路径上找到函数.First,则会执行.First()

因此,在任何其他函数的情况下,lkf将在函数的环境中创建,该函数在函数退出时被销毁。

相反,您可以在lkf之外定义.First

lkf <- function(d,p) grep(p, names(d), value = TRUE)

.First <- function() {
   [...]
}