1 Goal


The goal of this tutorial is to learn how to name variables inside loops or using arguments. This could be useful if we don’t know how many variables we want to create.


2 How to create a variable giving the name as an argument


# We can create a variable and assign a value
my_variable <- 5
my_variable
## [1] 5
# Now we can create a variable by name
assign("my_string", "Hello World")

# We check if the variable exists on this environment: TRUE if exists
exists("my_string")
## [1] TRUE
# Now we retrieve the value stored inside this variable
get("my_string")
## [1] "Hello World"

3 Create variables inside a loop


# We can use paste0 to create strings using the value of the index of the loop
for(i in 1:5){
  assign(paste0("number",i), as.integer(i))
}

# We can list all the objects that have been created in this tutorial
ls()
## [1] "i"           "my_string"   "my_variable" "number1"     "number2"    
## [6] "number3"     "number4"     "number5"
# Let's store this list into a variable
my_objects <- ls()

# Now we only keep the ones that start with number
my_objects <- my_objects[grep("number", my_objects)]
my_objects
## [1] "number1" "number2" "number3" "number4" "number5"
# Now we can get the values stored inside this variables
# Notice in this step that nothing is hardcoded
# This loop will work no matter which is the length or the content of this list of objects
for(i in 1:length(my_objects)){
  print(my_objects[i])
  print(get(my_objects[i]))
  
}
## [1] "number1"
## [1] 1
## [1] "number2"
## [1] 2
## [1] "number3"
## [1] 3
## [1] "number4"
## [1] 4
## [1] "number5"
## [1] 5

4 Conclusion


In this tutorial we have learnt how to use the assign function to store information in variables with names defined by argument. This is very useful if we want to name this variables after text or name variables using a loop.