2

I have several functions in my .Rprofile file:

f1 <- function() { ...... }
f2 <- function() { ...... }
g <- function() { ...... }

The functions f1 and f2 are helper functions for g, and I don't want them in the global environnement. How could I do?

A solution is:

g <- function() { 
  f1 <- function() { ...... }
  f2 <- function() { ...... }
  ......
}

but I don't like it.

zx8754
  • 52,746
  • 12
  • 114
  • 209
Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225

4 Answers4

2

I would include everything in a call to local() (and explicitly assign g to the global environment). This way, .Rprofile is self-contained and does not depend on external code.

# .Rprofile
local({
  f1 <- function() "foo"
  f2 <- function() "bar"
  assign("g", function() c(f1(), f2()), envir = globalenv())
})
Joris C.
  • 5,721
  • 3
  • 12
  • 27
2

That's what we have packages for. Build a package containing your functions and load it in .Rprofile.

Roland
  • 127,288
  • 10
  • 191
  • 288
0

I think I found a solution. I put f1 and f2 in a file in another folder (in the inst folder since I'm in a package) and I do that in .Rprofile:

g <- function() {
  source("other/folder/file.R", local = TRUE)
  ......
}

Then when I run g, the functions f1 and f2 do not appear in the global environment.

Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225
0

I'm not sure if there are some obvious drawbacks, but maybe you can add a . at the beginning of the functions' name to hide them from the global environment:

.f1 <- function(...) {...}
.f2 <- function(...) {...}
g <- function(...) {...}
agila
  • 3,289
  • 2
  • 9
  • 20