Historically, populations resided in rural hamlets, but spatial limits eventually forced housing to expand vertically. The implication is that instead of having an address for ten separate homes (recycling the metaphor from variable assignment Chapter 29), there is now one address for the building along with a floor number.
A vector in programming is essentially a higher-level object that stores a sequence of the same type. To access any specific value, one only needs to know the name of the building and the floor number.
This analogy only holds in progamming when each floor—called an element—is of the same type (all numbers, all logical values, or all strings). If the elements are heterogeneous, a list is used instead (Chapter 39). Vector indexing relies on integers (Chapter 3).
The key point is that a vector is a new type of object constructed from a sequence of elementary types. It shares a similar structure to basic variables: variable name, assignment operator, and value–which is a now sequence. Values can be retrieved based on their order in the sequence. In practice, vectors are used to store data corresponding to a single variable (Chapter 16).
Formal
To construct a vector in R, the syntax c() —short for concatenate—is used.
vector_name <-c(object1, object2, ..., objectn)
The length of a vector is the number of elements it contains and can be retrieved with length().
To access the \(p^{th}\) element of a vector, square brackets [] are used. In the example above, vector_name[2] returns object2. The positional order is called the index and must be an integer.
In R, a negative index excludes the element. For example, vector_name[-2] removes object2 from the output.
Examples
Constructing vectors.
# Creating a Boolean vectorc(FALSE, FALSE, TRUE)
[1] FALSE FALSE TRUE
# Creating an integer vectorc(2L, 1L, 4L)
[1] 2 1 4
# Creating a character vectorc("Hello", "world", "Goodbye")
[1] "Hello" "world" "Goodbye"
# Assigning a vector to a variablemy_vector <-c("Hello", "world", "Goodbye")
Accessing single values.
# Outputting the first elementmy_vector[1]
[1] "Hello"
# Outputting the second elementmy_vector[2]
[1] "world"
Accessing multiple values by subsetting with a vector of indices.
# Outputting the first and second elementsmy_vector[c(1, 2)]
[1] "Hello" "world"
# Outputting the second and first elements in reverse ordermy_vector[c(2, 1)]
[1] "world" "Hello"
# Storing the indices as a vectorvector_index <-c(2, 3)my_vector[vector_index]
[1] "world" "Goodbye"
Constructing vectors from existing vectors.
vec1 <-c(1, 4, 5)vec2 <-c(10, 11, 12)# Combine the two vectorsvec_combined <-c(vec1, vec2)# Append a single value to the existing vectorvec_combined <-c(vec_combined, 123)
Deleting one or more elements.
# Remove the first elementvec_combined[-1]
[1] 4 5 10 11 12 123
# Remove the first and fourth elementsvec_combined[c(-1, -4)]
[1] 4 5 11 12 123
Notice that these operations do not modify the stored variable; they return and display the subsetted vector.
# Extract and store in a new variablesub_vector <- vec_combined[c(-1, -4)]sub_vector
[1] 4 5 11 12 123
One can overwrite the original variable by reassigning the subsetted result, but note that the previous values cannot be recovered once overwritten.
# Overwrite the variable with the subsetted resultvec_combined <- vec_combined[c(-1, -4)]vec_combined
[1] 4 5 11 12 123
Tips and warnings
A vector of length n can be seen as a n-dimensional object.
All elements in a vector must be of the same type. If different data types are combined, R automatically converts—or coerces—the values according to a strict hierarchy: Logical < Integer < Numeric < Character. Values lower in this hierarchy are converted to the higher type. The function structure is used to assess the type of vector.
Booleans to Integer
# Boolean values are coerced to Integer (TRUE becomes 1L, FALSE becomes 0L)str(c(TRUE, FALSE, 4L))
int [1:3] 1 0 4
Integer to Numeric
# Boolean values are coerced to Numeric (TRUE becomes 1, FALSE becomes 0)str(c(TRUE, FALSE, 4))
num [1:3] 1 0 4
# Integers are coerced to Numeric (1L and 2L become numeric 1 and 2)str(c(1L, 2L, 4))
num [1:3] 1 2 4
Numeric to Character
# Boolean values are coerced to Character (TRUE becomes "TRUE")str(c(TRUE, TRUE, "text"))
chr [1:3] "TRUE" "TRUE" "text"
# Both Boolean and Numeric values are coerced to Character (TRUE becomes "TRUE", 1.2 becomes "1.2")str(c(TRUE, 1.2, "text"))
chr [1:3] "TRUE" "1.2" "text"
This coercion can cause issues when importing data into R. If a column is supposed to be a numeric vector, but a single element cannot be parsed as numeric (e.g., the letter O instead of the number 0), R will convert all elements to character.
When printing long vectors in R, the bracketed numbers shown at the beginning of each line—such as [1], [38], or [75]—indicate the index of the first element displayed on that specific line. Because output wraps according to the width of the console window, these index markers dynamically adjust to help track element positions across multiple lines.
The elementary object (Chapter 30, Chapter 32, Chapter 33) are all considered as vector in R. The [1] means R displays the first element
# 1 is a numeric vector of length 11
[1] 1
# Hello is a character vector of length 1"Hello"
[1] "Hello"
# TRUE is a logical vector of length 1TRUE
[1] TRUE
In R, using a numeric index—such as vector_name[1.2]—behaves identically to vector_name[1]. By design, R automatically truncates the decimal portion (rounding down toward zero) to reduce the value to an integer index. While this index behavior can be convenient, it can also mask unintended non-integer values during indexing operations.
Elements within a vector can also be accessed by name rather than position. This approach is useful for short vectors or specialized operations where named elements make code clearer and eliminate the need to track index positions. Assigning labels creates a named vector by attaching a names attribute to the underlying elements.
# Create a named numeric vector representing room dimensionsroom <-c(width =15, height =12)# Display the attributes attached to the vectorattributes(room)
$names
[1] "width" "height"
# Access an element by its assigned name instead of an index positionroom["width"]
width
15
Notice that when creating a named vector, element names are assigned using unquoted syntax similar to variable assignment (e.g., width = 15), but when subsetting by name, the name must be provided as a character string (e.g., room[“width”])
In R, a factor in R is a data structure used to store character vector. It stores character values as vector of integer codes mapped to a fixed set of predefined character labels called levels. It is memory efficient and also support ordering the values
# Constructing a character vectormy_vector <-c("a", "c", "a", "b")# Transforming a vector to a factormy_factor <-as.factor(my_vector)# The ouptput is the same expect the addition of levelsmy_factor
[1] a c a b
Levels: a b c
# But the structure of a factor is differentstr(my_factor)
Factor w/ 3 levels "a","b","c": 1 3 1 2
Each level corresponds to an integer: a to 1, b to 2 and c to 3. The sequence 1 3 1 2 is then reconstructed from that mapping. This is memory efficient because instead of storing a sequence of “characters” which takes more memory than a sequence of integer.
# Constructing an ordered factormy_factor_ordered <-factor( my_vector,levels =c("b", "a", "c"),ordered =TRUE)# Printing the valuemy_factor_ordered
[1] a c a b
Levels: b < a < c
# Examining the structurestr(my_factor_ordered)
Ord.factor w/ 3 levels "b"<"a"<"c": 2 3 2 1
Ordering is pointless in the example but could be useful for ordinal such as age class or altitudinal class.