# create a numeric vector
num_vect <- c(1, 2, 3)
# display the vector
num_vect[1] 1 2 3
# check if it is a vector
is.vector(num_vect)[1] TRUE
# check data type
class(num_vect)[1] "numeric"
Learning Objectives: After this chapter you will be able to:
- Create atomic vectors of type numeric, integer, character, and logical.
- Name vector elements, and select elements by name.
- Apply arithmetic across a whole vector at once.
- Explain the coercion order
logical→integer→double→character.- Subset using positive, negative, and logical indices.
- Find missing values with
is.na()and exclude them withna.rm = TRUE.
Vector is the most basic data structure in R. It is a sequence of elements of the same data type. If the elements are of different data types, they will be coerced to a common type that can accommodate all the elements. Vectors are generally created using c() (concatenate function), although depending on the data type of vector being created, other methods can be used.
We will create a numeric vector using c() but you can use any function that creates a sequence of numbers. After that we will use is.vector() to check if it is a vector and class to check the data type.
[1] 1 2 3
[1] TRUE
[1] "numeric"
Let us look at other ways to create a sequence of numbers. We leave it as an exercise to the reader to understand the functions using help.
Creating an integer vector is similar to numeric vector except that we need to instruct R to treat the data as integer and not numeric or double. We will use the same methods we used for creating numeric vectors. To specify that the data is of type integer, we suffix the number with L.
A character vector may contain a single character, a word or a group of words. The elements must be enclosed in single or double quotations.
A vector of logical values will either contain TRUE or FALSE or both.
[1] TRUE FALSE TRUE TRUE FALSE
[1] "logical"
In fact, you can create an integer vector and coerce it to type logical.
It is possible to name the different elements of a vector. The advantage of naming vector elements is that we can later on use these names to access the elements. Use names() to specify the names of a vector. You can specify the names while creating the vector or add them later.
Vectors are homogeneous i.e. all the elements of the vector must be of the same type. If we try to create a vector by combining different data types, the elements will be coerced to the most flexible type. The below table shows the order in which coercion occurs.
character data type is the most flexible while logical data type is the least flexible. If you try to combine any other data type with character, all the elements will be coerced to type character. In the absence of character data, all elements will be coerced to numeric. Finally, if the data does not include character or numeric types, all the elements will be coerced to integer type.
To summarize, below is the order in which coercion takes place:
logical → integer → double/numeric → character
R coerces toward the most flexible type. If a vector contains a character element, everything becomes character. Without character, elements coerce to numeric. Without numeric, elements coerce to integer.
In this section, we look at simple operations that can be performed on vectors in R. Remember that the nature of the operations depends upon the type of data. Below are a few examples:
In the previous case, the length i.e. the number of elements in the vectors were same. What happens if the length of the vectors are unequal? In such cases, the shorter vector is recycled to match the length of the longer vector. The below example should clear this concept:
Missing data is a reality. No matter how careful you are in collecting data for your analysis, chances are always high that you end up with some missing data. In R missing values are represented by NA. In this section, we will focus on the following:
We first create a vector with missing values. After that, we will use is.na() to test whether the data contains missing values. is.na() returns a logical vector equal to the length of the vector being tested. Another function that can be used for detecting missing values is complete.cases(). Below is an example:
In the presence of missing data, all computations in R will return NA. To avoid this, we might want to remove the missing data before doing any computation. na.omit() will remove all missing values from the data. Let us look at an example:
To exclude missing values from computations, use na.rm and set it to TRUE.
Common Mistake:
mean()on a vector containingNAreturnsNA, not the mean of the values that are present. Addna.rm = TRUEto drop missing values first, and check whether dropping them is defensible for your data.
One of the most important steps in data analysis is selecting a subset of data from a bigger data set. Indexing helps in retrieving values individually or a set of values that meet a specific criteria. In this chapter, we look at various ways of indexing/subsetting vectors.
[] is the index operator in R. We can use various expressions within [] to subset data. In R, index positions begin at 1 and not 0. To begin with, let us look at values in different index positions:
# fixed seed so this chapter re-renders deterministically
set.seed(42)
# random sample of 10 values
vect1 <- sample(10)
vect1 [1] 1 5 10 8 2 4 6 9 7 3
[1] 10
[1] 6
[1] 8 7 4 1 5 10 2 6 9 3
integer(0)
[1] 10
[1] NA
In the first case, we specified the index as 0 and in the second case we used the index 11, which is greater than the length of the vector. R returns an empty vector in the first case and NA in the second case.
Using a negative index will delete the value in the said index position. Unlike other languages, it will not index elements from the end of the vector counting backwards. Let us look at an example to understand how negative index works in R:
Common Mistake:
vect1[-3]does not mean “the third element from the end”. A negative index deletes that position. Usetail(vect1, 3)when you actually want the last three elements.
If we do not specify anything within [], all the elements in the vector will be returned. We can specify the index elements using any expression that generates a sequence of integers. Let us look at a few examples:
[1] 3 1 2 6 10 8 4 5 7 9
[1] 3 1 2 6 10 8 4 5 7 9
[1] 3 1 2 6 10
[1] 10 8 4 5 7 9
If you are using the colon to generate the index positions, you will have to specify both the starting and ending position, else, R will return an error.
What if we want elements that are not in a sequence as we saw in the last example? In such cases, we have to create a vector using c() and use it to extract elements from the original vector. Below is an example:
Edit the code below and press Run. It executes entirely in your browser via WebR — no R installation needed. The runtime downloads once, on this page only.
Vectors can be subset using the name of the elements. When using name of elements for subsetting, ensure that the names are enclosed in single or double quotations, else R will return an error. Let us look at a few examples:
Logical values can be used to subset vectors. They are not very flexible but can be used for simple indexing. In all of the below examples, the logical vectors are recycled to match the length of the vector from which we subset data:
[1] 6 2 4 3 10 5 9 7 8 1
[1] 6 2 4 3 10 5 9 7 8 1
integer(0)
[1] 6 4 10 9 8
[1] 2 3 5 7 1
Logical expressions can be used to extract elements that meet specific criteria. This method is most flexible and useful as we can combine multiple conditions using relational and logical operators. Before we use logical expressions, let us spend some time understanding comparison and logical operators as we will be using them extensively hereafter.
When you create an expression using a comparison operator, the output is always a logical value i.e. TRUE or FALSE. Let us see how we can use comparison operators to subset data:
[1] 10 8 5 1 7 4 6 2 9 3
[1] TRUE TRUE FALSE FALSE TRUE FALSE TRUE FALSE TRUE FALSE
[1] 10 8 7 6 9
[1] TRUE TRUE TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE
[1] 10 8 5 7 6 9
[1] FALSE FALSE FALSE TRUE FALSE TRUE FALSE TRUE FALSE TRUE
[1] 1 4 2 3
[1] FALSE FALSE TRUE TRUE FALSE TRUE FALSE TRUE FALSE TRUE
[1] 5 1 4 2 3
[1] FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[1] 5
[1] TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
[1] 10 8 1 7 4 6 2 9 3
Let us combine comparison and logical operators to create expressions and use them to subset vectors:
[1] 4 9 3 8 5 6 10 2 1 7
[1] 4 9 3 5 6 2 1 7
[1] 4 3 8 5 6 10 2 1
Knowledge Check: Index positions start at 1 What does vect1[3] return, and what does vect1[0] return?
Answer: vect1[3] returns the third element. vect1[0] returns an empty vector.
vect1[1]. Position 0 does not exist, so you get nothing back rather than the first element the way a 0-based language would give you.
Knowledge Check: Out of range indices vect1 has 10 elements. What does vect1[11] return?
Answer: NA.
NA instead. An empty result means “you asked for a position that cannot exist”; NA means “that element is missing”.
Knowledge Check: Negative indices delete What does vect1[-3] do — return the third element from the end, or something else?
Answer: It drops the third element and returns everything else.
Explanation: Unlike Python and most other languages, R does not count backwards from the end for you. A negative index removes that position, sovect1[-3] is “all elements except the third”. Use tail(vect1, 3) if you actually want the last three.
Knowledge Check: Coercion to the most flexible type What is the data type of c(1, 1L, 'one', TRUE)?
Answer: character, giving c("1", "1", "one", "TRUE").
logical → integer → double/numeric → character, always toward the most flexible type. The single 'one' forces everything to character.
Knowledge Check: Coercion without a character element What is the data type of c(1, 1L, TRUE)?
Answer: numeric (double), giving c(1, 1, 1).
character present, the most flexible type available is numeric, so the integer and the logical are promoted to double. You only fall back to integer when the data contains neither character nor numeric, as in c(1L, TRUE).
Knowledge Check: Missing values in a computation What does mean(c(1, 3, NA, 5, 2)) return?
Answer: NA. Use mean(c(1, 3, NA, 5, 2), na.rm = TRUE) to get 2.75.
NA means “unknown”, not “zero”, so one unknown value makes the whole mean unknown. na.rm = TRUE drops the missing values first, leaving 1, 3, 5, 2 — whose mean is 11 / 4 = 2.75. Decide deliberately whether dropping missing values is appropriate for your data.