# 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"
Practise this interactively in Course 1 (Introduction to R), lesson 3
Learning Objectives: After this chapter you will be able to:
- Create numeric, integer, character, and logical vectors.
- 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 by position, including negative positions, and by comparisons.
- 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, R coerces them to a common type that can accommodate all of them. We generally create vectors using c(), the concatenate function. Depending on the data type, we can also use other methods.
We will create a numeric vector using c(), but you can use any function that creates a sequence of numbers. We will then 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 creating a numeric vector, except that we instruct R to treat the data as integer and not numeric or double. We use the same methods as before. 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. We enclose the elements in single or double quotes:
A logical vector contains TRUE, 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.
We can name the elements of a vector. The advantage is that we can later use these names to access the elements. Use names() to specify the names of a vector. We can specify the names while creating the vector or add them later.
Vectors are homogeneous: all the elements of a vector must be of the same type. If we create a vector by combining different data types, R coerces the elements to the most flexible type.
character is the most flexible data type while logical is the least flexible.
To summarize, coercion takes place in this order:
logical → integer → double/numeric → character
R coerces toward the most flexible type. If a vector contains a character element, everything becomes character. Without character, the elements become numeric; without numeric, they become integer.
Let us look at simple operations we can perform on vectors in R. The nature of the operations depends upon the type of data. In the example below, we add, subtract, multiply and divide two vectors:
In the previous case, the length, i.e. the number of elements in the vectors, was the same. What happens if the lengths are unequal? In such cases, R recycles the shorter vector to match the length of the longer one. In the example below, we repeat the four operations on two vectors of different lengths:
Missing data is a reality. No matter how careful you are in collecting data for your analysis, you may end up with some missing values. 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. Then we 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. complete.cases() is another function that detects missing values. In the example below, we use both functions on the same vector:
Most summary functions (mean(), sum(), max()) return NA when any value is missing. To avoid this, we can remove the missing data before any computation. na.omit() removes all missing values from the data. Let us look at an example:
Whenever you want to exclude missing values from a computation, 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 retrieves values individually or a set of values that meet a specific criterion. In this chapter, we look at various ways of indexing vectors.
[] is the index operator in R. We can use various expressions within [] to subset data. In R, positions begin at 1 and not 0. Let us look at the values in different 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 used the position 0, and in the second case the position 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.
A negative position drops the value at that position. Unlike other languages, R does not count backwards from the end of the vector. Let us look at an example to understand how a negative position 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 [], R returns all the elements in the vector. We can specify the positions 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 we use the colon to generate the positions, we have to specify both the starting and the ending position. Otherwise, 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 create a vector using c() and use it to extract values from the original vector:
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.
First run downloads the R runtime and any required packages (about 20 s); later runs reuse them.
We can subset vectors using the names of the elements. When we use the names of the elements for subsetting, the names must be enclosed in single or double quotes; otherwise, R will return an error. Let us look at a few examples:
We can use logical values to subset vectors. They are not very flexible but can be used for simple indexing. In all the examples below, R recycles the logical vectors 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
We can use logical expressions to extract elements that meet specific criteria. This method is the 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; we will use them extensively hereafter.
A comparison operator always returns a logical value, 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.
is.na() to find missing values and na.rm = TRUE to exclude them from summaries.Next: Dataframes in R
Practise interactively: Course 1, lesson 3