Variables are used in R to store information for computational purposes. It seems that there is almost no limit to what can be stored in a variable. To make a variable, you need to know the following information.
- The name you want to give the variable
- The information you want to store in the variable
Here is an example,
You want to make a variable that will store the following test score: 80, 81, 82, 83, 84, 85. You want to call the variable test_scores. Here is what we know
- The name of the variable is test_scores
- It will contain the values of 80, 85, 90, 95, 100
Here is how this would look in R.
> test_score <- 80:85
There are a few things to explain
- the <- sign means “assigned to” in other words, the variable name on the left of the <- sign is being assigned to the values 80:85.
- The colon sign stands for a sequence. We wanted all whole numbers from 80 to 85 and the colon sign provides this information.
- Both the <- and : are known as operators in R. Operators symbols you place between numbers in order to make a calculation.
Know, type test_scores into the R console and press enter. You should see the following.
> test_scores  80 81 82 83 84 85
R now shows you everything that is stored in the variable. We can also created other variables and perform calculations through the use of variables. For example, let’s say that you want to add 5 points of extra credit to the scores of the test. To do this let’s make a variable called extra_credit and add test_scores to extra_credit
> extra_credit <- 5 > test_scores + extra_credit  85 86 87 88 89 90
As you can see, R took the values of test_scores and add extra_credit to each value in test_scores. This is much faster than entering each value separately to calculate it. We can also make a new variable for the new scores and we can call it revised_test_scores Let’s try
> revised_test_scores <- test_scores + extra_credit > revised_test_scores  85 86 87 88 89 90
Variables can also be used for text. The only difference is that you must put quotes around the words. Otherwise, the computer will think the words are numbers, which does not make sense. Below is an example,
> h <- "Howdy" > h  "Howdy"
Lastly, variables can be used to store vectors. This is very useful in saving a lot of time in performing calculations. We will now make the variable student_names and assigned a vector to it containing the names of students.
> student_names <- c("David", "Edward", "John") > student_names  "David" Edward" "John"
This is only the beginning of some of the amazing features of R.