R vectors
last modified November 19, 2026
A vector is an ordered collection of values of the same type, and it is the basic data structure of R. Even a single number is a vector of length one, and a data frame is built from vectors that share a length. This article shows how to create vectors, build sequences and repetitions, select elements by position and by condition, attach names, change elements, and sort the result. The operations that compute with whole vectors were covered in the vectorization article.
Creating vectors
The function c, short for combine, joins its arguments into one
vector. The colon operator builds a sequence of consecutive numbers. Both
produce an atomic vector, which is a vector whose elements are single
values rather than other vectors. If the arguments have different types, R
converts them to a common type before combining them.
scores <- c(72, 85, 90, 66, 78)
counts <- 1:5
labels <- c("a", "b", "c")
cat("scores:", scores, "\n")
cat("counts:", counts, "\n")
cat("labels:", labels, "\n")
cat("length:", length(scores), "\n")
The three vectors have different types: double, integer, and character. The
function length returns the number of elements, which is five for
the scores. An atomic vector has no dimensions beyond its length; the matrix
and array articles add dimensions on top of the same underlying vector.
$ Rscript combine.R scores: 72 85 90 66 78 counts: 1 2 3 4 5 labels: a b c length: 5
Building sequences
The colon operator always steps by one or minus one. The function
seq is more flexible: it accepts a step with by, a
total number of values with length.out, or another vector whose
length should be matched. It is the tool to reach for when the colon cannot
express the sequence.
print(seq(1, 10, by = 2)) print(seq(0, 1, length.out = 5)) print(seq(10, 1, by = -3))
The first call counts from one to ten in steps of two. The second divides the interval from zero to one into five equally spaced values, including both end points. The third counts down with a negative step. A step that does not divide the interval evenly stops at the last value that does not pass the end point.
$ Rscript sequences.R [1] 1 3 5 7 9 [1] 0.00 0.25 0.50 0.75 1.00 [1] 10 7 4 1
Repeating values
rep repeats a value or a whole vector. The argument
times repeats the complete vector, while each
repeats every element before moving to the next one. The distinction is easy to
see when the vector contains more than one value.
print(rep(1:3, times = 2))
print(rep(1:3, each = 2))
print(rep("x", 4))
times = 2 produces the pattern 1, 2, 3 twice, while
each = 2 produces every value twice in a row. Both arguments can
be combined, and rep also accepts a vector of lengths, which
repeats each element a different number of times. The function is useful for
building labels and group indicators.
$ Rscript repeats.R [1] 1 2 3 1 2 3 [1] 1 1 2 2 3 3 [1] "x" "x" "x" "x"
Indexing
An index is a position used to select elements. R counts from one, so the first element has index one and the last has index equal to the length. A positive index selects, a negative index excludes, and a logical vector selects the positions where it is true. The brackets around the index are called the subset operator.
scores <- c(72, 85, 90, 66, 78)
cat("first:", scores[1], "\n")
cat("last:", scores[length(scores)], "\n")
cat("middle:", scores[2:4], "\n")
cat("without first:", scores[-1], "\n")
cat("top:", scores[scores >= 85], "\n")
scores[2:4] is a vector of three indices and returns three
elements. scores[-1] returns everything except the first element;
the minus sign does not count from the end as it does in some other languages.
The last line keeps the elements whose comparison with 85 is true, which is the
most common way to filter data in R.
$ Rscript indexing.R first: 72 last: 78 middle: 85 90 66 without first: 85 90 66 78 top: 85 90
Names
Elements can carry names, which are labels stored in a names
attribute next to the values. Names are written as name = value
inside c, and an element can then be selected by its name in
quotes. Names do not change the type of the vector or the way arithmetic
works; they only label the elements.
scores <- c(Ada = 72, Grace = 85, Barbara = 90)
print(scores)
cat("Grace:", scores["Grace"], "\n")
print(names(scores))
The printout aligns the values under their names, which makes a named vector
read like a small table. names returns the labels as a character
vector. Selecting by name returns a vector with the name attached, but
cat prints only the value, which is why the third line shows just
85.
$ Rscript naming.R
Ada Grace Barbara
72 85 90
Grace: 85
[1] "Ada" "Grace" "Barbara"
Changing elements
Assignment through an index replaces one element and leaves the rest of the vector intact. Assigning to an index beyond the current length extends the vector, filling the gap with missing values. R copies the vector when it is modified, so the old object is not changed in place.
scores <- c(72, 85, 90, 66, 78)
scores[4] <- 70
scores[6] <- 88
cat("scores:", scores, "\n")
cat("length:", length(scores), "\n")
The fourth score changes from 66 to 70, and the assignment at index six appends
88 at the end. Growing a vector one element at a time is inefficient for large
data, because each assignment may allocate a new vector; preallocate the final
length and fill it by index when a loop must build a vector. The
append function inserts elements in the middle when position
matters.
$ Rscript editing.R scores: 72 85 90 70 78 88 length: 6
Sorting and ordering
sort returns the values in ascending order, and
decreasing = TRUE reverses the order. rev reverses
the current order without sorting. order is different: it returns
the positions that would put the vector in order, which is useful when several
vectors must be rearranged together.
scores <- c(72, 85, 90, 66, 78)
cat("sorted:", sort(scores), "\n")
cat("decreasing:", sort(scores, decreasing = TRUE), "\n")
cat("reversed:", rev(scores), "\n")
cat("order:", order(scores), "\n")
cat("by order:", scores[order(scores)], "\n")
The order vector is 4, 1, 5, 2, 3 because the smallest value is at position four, the next at position one, and so on. Indexing the original vector with that vector produces the sorted values. The same idea sorts the rows of a data frame by one column, and the subsetting article later in the series applies it to tables.
$ Rscript sorting.R sorted: 66 72 78 85 90 decreasing: 90 85 78 72 66 reversed: 78 66 90 85 72 order: 4 1 5 2 3 by order: 66 72 78 85 90
A complete example
The next script ranks five students by score. The scores are named, so sorting keeps the names attached and the result reads as a small league table. The first three positions are selected with a range index.
scores <- c(Ada = 72, Grace = 85, Barbara = 90, Alan = 66, Edsger = 78)
ranking <- sort(scores, decreasing = TRUE)
top3 <- ranking[1:3]
cat("top three:\n")
print(top3)
sort keeps the names, and ranking[1:3] keeps the
first three elements together with their labels. Barbara leads with 90, Grace
follows with 85, and Edsger takes third place with 78. The same three steps,
name, sort, and select, work for any vector of measurements.
$ Rscript ranking.R
top three:
Barbara Grace Edsger
90 85 78
Next steps
The lists article relaxes the rule that every element has the same type, and the matrices article adds rows and columns to the vector. The subsetting article later in the series covers the more advanced forms of the bracket operator, and the strings article shows how to work with vectors of text.
Source
An Introduction to R: vectors and assignment
The R Language Definition: indexing
R documentation: extract or replace parts of an object
R documentation: sorting and ordering
In this article we have built vectors with c and the colon,
generated sequences with seq, and repeated values with
rep. We selected elements by position, by exclusion, and by a
logical condition, attached names, replaced and appended elements, and sorted
the result with sort and order. The series continues
with R lists.
Author
List all R Language tutorials.