Skip to content

R base vector API

R's base vector functions — vectors are the fundamental data structure in R, holding elements of one type.

1 class · 7 methods

vector functions

7 methods

Base R functions for creating, inspecting and transforming vectors.

length(x) -> integer

Returns the number of elements in a vector or list.

Parameters

NameTypeDescription
xanyAn R object (vector, list, etc.).

Returns

integer

Example

r
x <- c(1, 2, 3, 4)
length(x)  # 4
length(character())  # 0
c(...) -> vector

Combines values into a vector or list, coercing to a common type.

Parameters

NameTypeDescription
...anyObjects to combine.

Returns

vector

Example

r
x <- c(1, 2, 3)
y <- c("a", "b", "c")
z <- c(x, 4, 5)  # 1 2 3 4 5
x[i] (subscript)

Extracts elements by integer, logical, or character index. Negative indices drop elements.

Parameters

NameTypeDescription
iinteger|logical|characterIndex vector.

Returns

vector

Example

r
x <- c(10, 20, 30, 40)
x[2]        # 20
x[c(1, 3)]  # 10 30
x[x > 15]   # 20 30 40
x[-1]       # 20 30 40 (drop first)
sort(x, decreasing = FALSE) -> vector

Returns a sorted copy of the vector.

Parameters

NameTypeDescription
xvectorVector to sort.
decreasinglogicalSort descending (default FALSE).

Returns

vector

Example

r
x <- c(3, 1, 4, 1, 5)
sort(x)                  # 1 1 3 4 5
sort(x, decreasing = TRUE)  # 5 4 3 1 1
unique(x) -> vector

Returns a vector with duplicate elements removed, preserving first occurrences.

Parameters

NameTypeDescription
xvectorInput vector.

Returns

vector

Example

r
x <- c(1, 2, 2, 3, 3, 3)
unique(x)  # 1 2 3
rev(x) -> vector

Returns a copy of the vector with elements in reverse order.

Parameters

NameTypeDescription
xvectorInput vector.

Returns

vector

Example

r
x <- c(1, 2, 3)
rev(x)  # 3 2 1
sum(..., na.rm = FALSE) -> numeric

Returns the sum of all values. Use na.rm = TRUE to ignore NA values.

Parameters

NameTypeDescription
...numericNumeric vectors to sum.
na.rmlogicalRemove NA values (default FALSE).

Returns

numeric

Example

r
sum(1, 2, 3)         # 6
sum(c(1, 2, NA))     # NA
sum(c(1, 2, NA), na.rm = TRUE)  # 3