1 Goal


The goal of this tutorial is to clean the environment to check that there is no clash between variables. This instruction can be written at the beginning of a script for safety.


2 Creating variables


for(i in 1:length(letters)){
  assign(letters[i],i)
}

# We can check now how many variables have we created
ls()
##  [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q"
## [18] "r" "s" "t" "u" "v" "w" "x" "y" "z"
# And their content
my_variables <- ls()
for(i in 1:length(my_variables)){
  print(paste(my_variables[i], get(my_variables[i])))
}
## [1] "a 1"
## [1] "b 2"
## [1] "c 3"
## [1] "d 4"
## [1] "e 5"
## [1] "f 6"
## [1] "g 7"
## [1] "h 8"
## [1] "i 9"
## [1] "j 10"
## [1] "k 11"
## [1] "l 12"
## [1] "m 13"
## [1] "n 14"
## [1] "o 15"
## [1] "p 16"
## [1] "q 17"
## [1] "r 18"
## [1] "s 19"
## [1] "t 20"
## [1] "u 21"
## [1] "v 22"
## [1] "w 23"
## [1] "x 24"
## [1] "y 25"
## [1] "z 26"

3 Clean entire environment


# We can see everything that has been loaded to the environment
ls()
##  [1] "a"            "b"            "c"            "d"           
##  [5] "e"            "f"            "g"            "h"           
##  [9] "i"            "j"            "k"            "l"           
## [13] "m"            "my_variables" "n"            "o"           
## [17] "p"            "q"            "r"            "s"           
## [21] "t"            "u"            "v"            "w"           
## [25] "x"            "y"            "z"
# We can clean everything on the environemnt with this simple instruction
rm(list = ls())

# We can check that nothing remains loaded
ls()
## character(0)

4 Conclusion


In this tutorial we have learnt how to clean all the variables from the environment. This could be really useful if we want to make sure that everything is clean before starting a project.