Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ls() in R not show global variables?

In the code below, LETTERS and letters are global, or in the global search path and reachable through another package (same thing!)

> LETTERS
 [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S"
[20] "T" "U" "V" "W" "X" "Y" "Z"
> letters
 [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
[20] "t" "u" "v" "w" "x" "y" "z"
> ls()
character(0)
> a <- "1 2 3"
> ls()
[1] "a"
> rm(a)
> ls()
character(0)
> 

like image 677
mda Avatar asked Sep 19 '12 15:09

mda


People also ask

Can R functions access global variables?

Functions can access global variables and modify them. Modifying global variables in a function is considered poor programming practice.

Why don't you use global variables?

A global variable can have no access control. It can not be limited to some parts of the program. Using global variables causes very tight coupling of code. Using global variables causes namespace pollution.

How do you get around a global variable?

The simplest way to avoid globals all together is to simply pass your variables using function arguments. As you can see, the $productData array from the controller (via HTTP request) goes through different layer: The controller receives the HTTP request. The parameters are passed to the model.


1 Answers

For the same reason it doesn't list all the exported functions in all the attached packages (from ?ls):

By default, the environment of the call to 'ls' or 'objects' is used.

Specify the environment that contains LETTERS and ls will print it's name.

# LETTERS is in there somewhere...
sapply(search(),ls)
like image 138
Joshua Ulrich Avatar answered Sep 30 '22 12:09

Joshua Ulrich