vector functions
7 methodsBase R functions for creating, inspecting and transforming vectors.
length(x) -> integerReturns the number of elements in a vector or list.
Parameters
| Name | Type | Description |
|---|---|---|
| x | any | An R object (vector, list, etc.). |
Returns
integer
Example
r
x <- c(1, 2, 3, 4)
length(x) # 4
length(character()) # 0c(...) -> vectorCombines values into a vector or list, coercing to a common type.
Parameters
| Name | Type | Description |
|---|---|---|
| ... | any | Objects 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 5x[i] (subscript)Extracts elements by integer, logical, or character index. Negative indices drop elements.
Parameters
| Name | Type | Description |
|---|---|---|
| i | integer|logical|character | Index 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) -> vectorReturns a sorted copy of the vector.
Parameters
| Name | Type | Description |
|---|---|---|
| x | vector | Vector to sort. |
| decreasing | logical | Sort 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 1unique(x) -> vectorReturns a vector with duplicate elements removed, preserving first occurrences.
Parameters
| Name | Type | Description |
|---|---|---|
| x | vector | Input vector. |
Returns
vector
Example
r
x <- c(1, 2, 2, 3, 3, 3)
unique(x) # 1 2 3rev(x) -> vectorReturns a copy of the vector with elements in reverse order.
Parameters
| Name | Type | Description |
|---|---|---|
| x | vector | Input vector. |
Returns
vector
Example
r
x <- c(1, 2, 3)
rev(x) # 3 2 1sum(..., na.rm = FALSE) -> numericReturns the sum of all values. Use na.rm = TRUE to ignore NA values.
Parameters
| Name | Type | Description |
|---|---|---|
| ... | numeric | Numeric vectors to sum. |
| na.rm | logical | Remove 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