# Progress Log 105 (R): Create and Name Vectors

### Vectors

• A sequence of data elements.
• Same basic data type.
• You can have character vectors, numeric vectors, logical vectors, etc.

### Create a Vector `c()`

#### Character Vector

Suppose you are playing a card game and record the suit of 5 cards you draw from a deck. A possible outcome and corresponding vector to contain this information could be like the one below.

We can also assign this character vector to a new variable. Here we will assign it to `drawn_suits`.

We can assert that it is a vector by typing `is.vector()`.

#### Integer Vector

Suppose you want to store how many cards of each suit remain after you drew the five cards. Let’s call this vector `remain`. There are 11 more spades, 12 more hearts, 11 diamonds, and all 13 clubs remain.

If you print `remain` in the console, it looks okay, but it’s not very informative. How does somebody else know that the first value corresponds to spades?

### Naming the vector

In R, you can use the `names()` function to name the vector.

#### Method 1

1. Let’s create another character vector, `suits`, that contains the strings “spades”, “hearts”, “diamonds”, and “clubs” – the names you want to give your vector elements.
1. `suits <- c("spades", "hearts", "diamonds", "clubs")`
2. Set the names of the elements of `remain` to the string in `suits`
1. `names(remain) <- suits`
3. Print `remain` in the console to make sure that the `suits` information is accompanied by the proper labels.

#### Method 2

If you don’t want to bother setting the names after creating the vector you can do as follows:

As you can see, it is not necessary to surround the names “spade”, “hearts”, “diamonds”, and “clubs” in this example with double quotes, although it works fine.

### Single value = vector

R does not provide a data structure to hold a single number or a single character string or any other basic data type: they’re all just vectors of length 1.

Examples:

You can check whether `my_apples` and `my_oranges` are vectors by using the `is.vector()` function.

You can check the length of vectors by using the `length()` function.

### Vectors are homogeneous

• Can only hold elements of the same type.
• Often called atomic vectors to differentiate them from lists (which can hold elements of different types).
• Automatic Coercion occurs if you try to build a vector that contains different data types. R will automatically coerce your vector so they then have the same data type.

### Coercion for vectors

Suppose now you are recording the ranks of the cards. You might want to combine the result of drawing 8 cards like this, creating a vector `drawn_ranks`.

If you now inspect this vector, you will see that the numeric vector elements have been coerced to characters, to end up with a homogeneous character vector.