Other sites

Create variables through assignments

[This article was first published on Quantargo Blog, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Usually you want to store vectors and other objects into variables so you can work with them more easily. Variables are like a box with a name. You can then refer to the name to see what is stored inside.

Learn how to create a variable

Use variables to store objects and vectors

Reuse assigned objects through a variable name

___

Assigning variables

Usually you want to use objects like vectors more than once. In order to save the trouble of retyping and recreating them all the time, we would like to save them somewhere and reuse them later.

To do this, we can assign them to a variable name. R uses the special arrow operator for assigning values to a variable. The arrow is simply the combination of a smaller-than character (<) and a minus sign (-).

Let’s take a look at an example, in which we assign a numeric vector to a variable named numbers:

numbers

Now we can use the variable’s name below to see its contents:

numbers

[1] 1 2 3 4 5 6 7 8 9

Note, that when we assign something to a variable that already exists, it gets overwritten. All previous contents are automatically removed:

numbers

[1] 10 11 12 13

Once you have defined a variable, you can use it just like you would use the underlying vector itself. In the following example we create two numeric vectors and assign them to the variables low and high. Then, we use these variables and concatenate the two vectors into a single one and assign it to the variable named sequence. Finally we call the sequence variable and inspect its contents:

low

[1] 1 2 3 4 5 6

As you can see, the vectors 1, 2, 3 and 4, 5, 6 stored in the variables low and high, were combined into a single vector that is now the the content of the variable sequence.

Exercise: Assign numeric vector to variable

Use the concatenate function c() and create a vector containing the numbers 2, 3, 5 and 7.