Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare variable with a dot at the begining in R [closed]

Tags:

r

The crux of the question is the same as the Title,

Somebody knows or could provide infromation about ".variables" in R?

.variable<-1
class(.variable) 
[1] 1
[1] "numeric"

As far as I know is like a hidden variable because it isnt appearing on the global environment of R studio.

So, the point would be to define:

  • What it is?
  • what is used for?
  • some examples
like image 206
PeCaDe Avatar asked Jan 09 '17 17:01

PeCaDe


Video Answer


1 Answers

The prefix dot notation in R specifies a hidden object that cannot be accessed directly through ls unless you use ls(all.names = TRUE). The purpose of this is for developers of R packages to have some way to hide the implementation details of their functions from users, making their package more user-friendly, as described more fully on R-bloggers (and quoted briefly here in case of link rot):

Lets say that you are developing the function use_me(). If the details you want the users to control are actually arguments of other functions used inside use_me(), then you can simplify your function by using the ... argument. This argument is very well explained at The three-dots construct in R (Burns, 2013). It is very useful and can greatly simplify your life as a developer. Plus, it reduces the length of your help pages, thus making your package more user friendly.

However, if some of the details in use_me() are not arguments to other functions, then the common strategy is to write two functions. One is a low level function with arguments for all the details which might or might not export. Then, you write a second function that is a wrapper for the low level function and pre-specifies values for all the details. See the next minimal example:

# Don't export this function
.use_me <- function(arg1, arg2, verbose = TRUE) {
    if(verbose) message(paste(Sys.time(), 'working'))
    pmax(arg1, arg2)
}

#' @export
use_me <- function(arg1, ...) {
    .use_me(arg1, 0, ...)
}

This is very similar to Python's use of the single underscore to prevent automatically loading objects from packages. In both cases the practice appears to be a naming convention - outside of their specified uses (in R's case, hiding the object in the environment) there isn't really any other outcome of using the notation (according to the comments on this post at least, and after scanning the documentation myself).

For examples of this in actual use, see the help for colSums or trace.

like image 77
HFBrowning Avatar answered Nov 03 '22 00:11

HFBrowning