简体   繁体   中英

I placed a function into my .Rprofile file, but it doesn't appear when I load R? I don't understand why

My .Rprofile file looks like this:

# 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")
}

I use the lkf function to quickly look for variables in a particular dataframe. It's modelled on the Stata lookfor function. However, it isn't available to me when I start R.

eg

> 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"

What have I done wrong?

From ?Startup ,

Next, if a function .First is found on the search path, it is executed as .First()

So as it is the case with any other function, lkf will be created in the function's environment which is destroyed as the function exits.

Instead, you could define lkf outside .First :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM