4.2 Variables
Variables allow us to store data in memory. When we store data in memory, we can also give it a name.
We create a variable using the assignment operator <- or =:
variable_name <- value
For our purposes, these are interchangeable. For example:
• composer <- "buxtehude"
• year = 1637
The variable name can be almost anything. Here are some general rules to consider when naming a variable:
• Variable names must start with a letter and consist of letters, numbers, ., and _
• Some words are considered “reserved” - i.e. they are already used by R to mean something and therefore cannot be a variable name. These include TRUE, if, NULL, etc. For a full list, check here.
4.2.1 Overwriting Variables
In the following code example, we assign two different values to the same variable name:
What is the value of myData? It will be "marigold". In the first line of code, we set myData equal to 3, but then in the next line, we overwrite that value and set myData equal to "margiold". The previous value of myData is erased and it is set to the new value.
Note that in doing so, we change not just the value of myData, but also the data type - it goes from numeric to character data.
We can also do this to update the value of a variable:
## [1] 15
Here, we set the variable a_number equal to 5. In the next line, we add 10 to its value, storing the result under the same name. a_number is now equal to 15.