2.2 Variables
Programming would be impossible without variables that allow us to store data for later use. Their value can be changed according to your need.
The recommended operator to assign data to a variable is <-. For example, you can assign the value 7 to x by typing
Note that the object x is created at the same time as the assignment, there is no need to define it first. But the same operator can also be used to overwrite the content of a variable. To illustrate that, we will use the function print() which prints the content of a variable.
As a helpful shortcut to print(), you may just type the name of a variable, which will call the function print() with default arguments.
A valid variable name in R consists of letters, numbers and the dot or underline characters. You can not name a variable that starts with a number. Also, variable names in R are case sensitive, so x <- 7 and X <- 7 are treated as two different things.
You can use variables to perform calculations the same way you can type numbers into the console:
Note that variables can also be assigned using the = operator as in
However, it is best practice to only use <- as the = can have multiple meanings in R.
2.2.1 Variable Names
Once you start working in R, you will notice that the amount of variables you are working with is adding up quite quickly. It is therefore important to give your variables sensible names that you will understand even if you have not looked at your code for a while. And while we used such names here frequently to illustrate concepts, x, a or b are not very telling names.
In fact, telling names are usually rather long and often consist of multiple words. Since R does not allow spaces within variable names, people generally use the underscore (random_number <- 856.5) or dot (random.number <- 856.5) to separate words, or use so-called camel case (randomNumber <- 856.5) for their variables. Of those, both Google and the tidyverse community recommend using underscores (_) for variable names as dots (.) have a special meaning in S3 classes (see MUCH later) and camel cases is preferred for functions. So why not stick to that?
2.2.2 Exercises: Variables
See Section 18.0.3 for solutions.
Assign the values 6.7 and -56.3 to variables
value_1andvalue_2, respectively.Use
help.search()to find out how to compute the square root of variables and compute the square root ofvalue_1andvalue_2.Use R to calculate \(\frac{2 a}{b} + a b\) using
value_1for \(a\) andvalue_2for \(b\) and assign the results to variablex.