Get startedGet started for free

What is a vector?

1. What is a vector?

So far, you have been working with one number at a time assigned to a variable. However, R is much more powerful than this. You are ready to learn about a core concept in R called vectors. A vector is a collection of data that are all the same type.

2. Vectors and stock prices

A good example of this is stock prices. You already know that you could store a single stock price in a variable named apple_stock. But, in the real world, you might have hundreds of daily Apple stock prices over the past year. It would be nice to have them all together in one structure. Vectors allow us to do this easily. To create a vector, we will use the 'c' function, which stands for _combine_. Here, we are combining three days worth of stock prices into one vector. Notice how there are commas separating each element in the vector. Now, typing in 'apple_stock' returns a vector of length three. The structure of this output should look somewhat familiar. In fact, the apple variable above is actually just a vector of length 1! You can see this by using one of the "is dot" functions --is-dot-vector - on apple. Doing this returns TRUE, indicating that apple is indeed a vector. You can create a vector from any single data type. Another example would be a vector of characters such as grocery, containing "apple", "orange" and "cereal". As long as it is a sequence of a single data type, you can vectorize it!

3. Vector names()

To be more descriptive, you might want to add names to your vector. Consider the apple_stock vector from before. If you knew that those were stock prices for Monday, Tuesday, and Wednesday of last week, wouldn't you want to include that information somehow? The names function let's you do just that. Here, we are adding names to apple_stock in the form of a character vector. Printing out apple_stock shows the more descriptive result.

4. Let's practice!

In the following exercises, you will practice creating and naming vectors and explore the idea of coercion. When you finish that, we will chat again about how to manipulate vectors. Good luck!