Vector

A vector is simply a list of items that are of the same type.

fruits <- c("banana", "apple", "orange")
numbers <- c(1, 2, 3)
numbers <- 1:10
log_values <- c(TRUE, FALSE, TRUE, FALSE)

Create an empty vector

methodsyntaxdescription
c()vec <- c()Creates a vector of type NULL.
vector()vec <- vector()Creates an empty vector with no specified type.
numeric()vec <- numeric()Creates an empty numeric vector.
character()vec <- character()Creates an empty character vector.
logical()vec <- logical()Creates an empty logical vector.
rep()vec <- rep()Creates an empty vector using the rep function.
vec <- numeric()
print(vec)  # Output: numeric(0)

vec <- vector()
print(vec)  # Output: NULL

vec <- character()
print(vec)  # Output: character(0)

vec <- logical()
print(vec)  # Output: logical(0)

To sort items in a vector alphabetically or numerically, use the sort() function sort(fruits)

Access Vectors

You can access the vector items by referring to its index number inside brackets []. The first item has index 1

fruits[1]
fruits[c(1, 3)]
# Access all items except for the first item
fruits[c(-1)]

To change the value of a specific item, refer to the index number: fruits[1] <- "pear"

create a vector with numerical values in a sequence: numbers <- seq(from = 0, to = 100, by = 20)