5  Vectors in R

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 with na.rm = TRUE.

5.1 Introduction

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.

5.2 Numeric Vector

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.

# 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"

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.

# using colon
vect1 <- 1:10
vect1
 [1]  1  2  3  4  5  6  7  8  9 10
# using rep
vect2 <- rep(1, 5)
vect2
[1] 1 1 1 1 1
# using seq
vect3 <- seq(10)
vect3
 [1]  1  2  3  4  5  6  7  8  9 10

5.3 Integer Vector

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:

# integer vector
int_vect <- c(1L, 2L, 3L)
int_vect
[1] 1 2 3
# check data type
class(int_vect)
[1] "integer"
# using colon
vect1 <- 1L:10L
vect1
 [1]  1  2  3  4  5  6  7  8  9 10
# using rep
vect2 <- rep(1L, 5)
vect2
[1] 1 1 1 1 1
# using seq
vect3 <- seq(10L)
vect3
 [1]  1  2  3  4  5  6  7  8  9 10

5.4 Character Vector

A character vector may contain a single character, a word or a group of words. We enclose the elements in single or double quotes:

# character vector
greetings <- c("hello", "good morning")
greetings
[1] "hello"        "good morning"
# check data type
class(greetings)
[1] "character"

5.5 Logical Vector

A logical vector contains TRUE, FALSE or both:

# logical vector
vect_logic <- c(TRUE, FALSE, TRUE, TRUE, FALSE)
vect_logic
[1]  TRUE FALSE  TRUE  TRUE FALSE
# check data type
class(vect_logic)
[1] "logical"

In fact, you can create an integer vector and coerce it to type logical.

# integer vector
int_vect <- rep(0L:1L, 3)
int_vect
[1] 0 1 0 1 0 1
# coerce to logical vector
log_vect <- as.logical(int_vect)
log_vect
[1] FALSE  TRUE FALSE  TRUE FALSE  TRUE
# check data type
class(log_vect)
[1] "logical"

5.6 Naming Vector Elements

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.

5.6.1 Method 1: Create vector and add names later

# create vector and add names later
vect1 <- c(1, 2, 3)

# name the elements of the vector
names(vect1) <- c("One", "Two", "Three")

# call vect1
vect1
##   One   Two Three 
##     1     2     3

5.6.2 Method 2: Specify names while creating vector

# specify names while creating vector
vect2 <- c(John = 1, Jack = 2, Jill = 3, Jovial = 4)

# call vect2
vect2
##   John   Jack   Jill Jovial 
##      1      2      3      4

5.7 Vector Coercion

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.

5.7.1 Case 1: Different Data Types

# vector of different data types
vect1 <- c(1, 1L, 'one', TRUE)

# call vect1
vect1
## [1] "1"    "1"    "one"  "TRUE"

# check data type
class(vect1)
## [1] "character"

5.7.2 Case 2: Numeric, Integer and Logical

# vector of different data types
vect1 <- c(1, 1L, TRUE)

# call vect1
vect1
## [1] 1 1 1

# check data type
class(vect1)
## [1] "numeric"

5.7.3 Case 3: Integer and Logical

# vector of different data types
vect1 <- c(1L, TRUE)

# call vect1
vect1
## [1] 1 1

# check data type
class(vect1)
## [1] "integer"

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.

5.8 Vector Operations

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:

5.8.1 Case 1: Vectors of same length

# create two vectors
vect1 <- c(1, 3, 8, 4)
vect2 <- c(2, 7, 1, 9)

# addition
vect1 + vect2
## [1]  3 10  9 13

# subtraction
vect1 - vect2
## [1] -1 -4  7 -5

# multiplication
vect1 * vect2
## [1]  2 21  8 36

# division
vect1 / vect2
## [1] 0.5000000 0.4285714 8.0000000 0.4444444

5.8.2 Case 2: Vectors of different length

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:

# create two vectors
vect1 <- c(2, 7)
vect2 <- c(1, 8, 5, 2)

# addition
vect1 + vect2
## [1]  3 15  7  9

# subtraction
vect1 - vect2
## [1]  1 -1 -3  5

# multiplication
vect1 * vect2
## [1]  2 56 10 14

# division
vect1 / vect2
## [1] 2.000 0.875 0.400 3.500

5.9 Missing Data

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:

  • test for missing data
  • remove missing data
  • exclude missing data from analysis

5.9.1 Detect missing data

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:

# vector with missing values
vect1 <- c(1, 3, NA, 5, 2)

# use is.na
is.na(vect1)
## [1] FALSE FALSE  TRUE FALSE FALSE

# use complete.cases
complete.cases(vect1)
## [1]  TRUE  TRUE FALSE  TRUE  TRUE

5.9.2 Omit missing data

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:

# vector with missing values
vect1 <- c(1, 3, NA, 5, 2)

# call vect1
vect1
## [1]  1  3 NA  5  2

# omit missing values
na.omit(vect1)
## [1] 1 3 5 2
## attr(,"na.action")
## [1] 3
## attr(,"class")
## [1] "omit"

5.9.3 Exclude missing data

Whenever you want to exclude missing values from a computation, use na.rm and set it to TRUE:

# vector with missing values
vect1 <- c(1, 3, NA, 5, 2)

# compute mean
mean(vect1)
## [1] NA

# compute mean by excluding missing value
mean(vect1, na.rm = TRUE)
## [1] 2.75

Common Mistake: mean() on a vector containing NA returns NA, not the mean of the values that are present. Add na.rm = TRUE to drop missing values first, and check whether dropping them is defensible for your data.

5.10 Index Vectors

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
# return third element
vect1[3]
[1] 10
# return seventh element
vect1[7]    
[1] 6

5.10.1 Out of range index

# random sample of 10 values
vect1 <- sample(10)
vect1
 [1]  8  7  4  1  5 10  2  6  9  3
# return value at index 0
vect1[0]
integer(0)
# length of the vector
length(vect1)
[1] 10
# out of range index
vect1[11]   
[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.

5.10.2 Negative Index

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. Use tail(vect1, 3) when you actually want the last three elements.

# random sample of 10 values
vect1 <- sample(10)
vect1
 [1]  9 10  3  4  5  6  1  2  8  7
# drop third element
vect1[-3]
[1]  9 10  4  5  6  1  2  8  7
# drop seventh element
vect1[-7]   
[1]  9 10  3  4  5  6  2  8  7

5.10.3 Subset Multiple 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:

# random sample of 10 values
vect1 <- sample(10)
vect1
 [1]  3  1  2  6 10  8  4  5  7  9
# return all elements
vect1[]
 [1]  3  1  2  6 10  8  4  5  7  9
# return first 5 values
vect1[1:5]
[1]  3  1  2  6 10
# return all values from the 5th position
end <- length(vect1)
vect1[5:end]
[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:

# random sample of 10 values
vect1 <- sample(10)
vect1
 [1]  5  4  2  8  3  1 10  7  6  9
# extract 2nd, 5th and 7th element
select <- c(2, 5, 7)
vect1[select]
[1]  4  3 10
# extract elements in position 1 to 4, 6 and 9
select <- c(1:4, 6, 9)
vect1[select]
[1] 5 4 2 8 1 6

Try it in your browser

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.

5.10.4 Subset Named Vectors

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:

vect1 <- c(score1 = 8, score2 = 6, score3 = 9)
vect1
score1 score2 score3 
     8      6      9 
# extract score2
vect1['score2']
score2 
     6 
# extract score1 and score3
vect1[c('score1', 'score3')]
score1 score3 
     8      9 

5.10.5 Subset using logical values

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:

# random sample of 10 values
vect1 <- sample(10)
vect1
 [1]  6  2  4  3 10  5  9  7  8  1
# returns all values
vect1[TRUE]
 [1]  6  2  4  3 10  5  9  7  8  1
# empty vector
vect1[FALSE]
integer(0)
# values in odd positions
vect1[c(TRUE, FALSE)]
[1]  6  4 10  9  8
# values in even positions
vect1[c(FALSE, TRUE)]
[1] 2 3 5 7 1

5.10.6 Subset using logical expressions

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.

5.10.6.1 Comparison Operators

A comparison operator always returns a logical value, TRUE or FALSE. Let us see how we can use comparison operators to subset data:

# random sample of 10 values
vect1 <- sample(10)
vect1
 [1] 10  8  5  1  7  4  6  2  9  3
# return elements greater than 5
vect1 > 5
 [1]  TRUE  TRUE FALSE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE
vect1[vect1 > 5]
[1] 10  8  7  6  9
# return elements greater than or equal to 5
vect1 >= 5
 [1]  TRUE  TRUE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE
vect1[vect1 >= 5]
[1] 10  8  5  7  6  9
# return elements lesser than 5
vect1 < 5
 [1] FALSE FALSE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE
vect1[vect1 < 5]
[1] 1 4 2 3
# return elements lesser than or equal to 5
vect1 <= 5
 [1] FALSE FALSE  TRUE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE
vect1[vect1 <= 5]
[1] 5 1 4 2 3
# return elements equal to 5
vect1 == 5
 [1] FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
vect1[vect1 == 5]
[1] 5
# return elements not equal to 5
vect1 != 5
 [1]  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
vect1[vect1 != 5]
[1] 10  8  1  7  4  6  2  9  3

5.10.7 Logical Operators

Let us combine comparison and logical operators to create expressions and use them to subset vectors:

# random sample of 10 values
vect1 <- sample(10)
vect1
 [1]  4  9  3  8  5  6 10  2  1  7
# return all elements less than 8 or divisible by 3
vect1[(vect1 < 8 | (vect1 %% 3 == 0))]
[1] 4 9 3 5 6 2 1 7
# return all elements less than 7 or divisible by 2
vect1[(vect1 < 7 | (vect1 %% 2 == 0))]
[1]  4  3  8  5  6 10  2  1

5.11 Practice Check

Knowledge Check: Index positions start at 1 What does vect1[3] return, and what does vect1[0] return?

Click to reveal answer

Answer: vect1[3] returns the third element. vect1[0] returns an empty vector.

Explanation: R counts positions starting at 1, so the first element is 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?

Click to reveal answer

Answer: NA.

Explanation: Index 0 returns an empty vector, but an index that is past the end of the vector returns 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?

Click to reveal answer

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, so vect1[-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)?

Click to reveal answer

Answer: character, giving c("1", "1", "one", "TRUE").

Explanation: Coercion runs 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)?

Click to reveal answer

Answer: numeric (double), giving c(1, 1, 1).

Explanation: With no 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?

Click to reveal answer

Answer: NA. Use mean(c(1, 3, NA, 5, 2), na.rm = TRUE) to get 2.75.

Explanation: 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.

Key points

  • A vector holds values of one type; mixing types can coerce its elements.
  • Name elements to select them by name as well as by position.
  • Positive indices select elements, negative indices exclude them, and logical indices keep matches.
  • Use 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