Vectors in R
Vectors are one of the fundamental data structures in R. They come in two flavors: atomic vectors and lists. Atomic vectors include logical vectors, integer vectors, double vectors, and character vectors. Lists, on the other hand, are a special type of vector that can contain elements of different types.
In this tutorial, we will explore these various types of vectors in R, how to create them, manipulate them, and use them in our R programs.
Atomic Vectors
Atomic vectors are the most basic R data types and every R object is a vector or includes vectors in its implementation.
Creating Atomic Vectors
You can create a vector in R using the c()
function, which stands for "concatenate". Here is an example of how to create an integer vector:
integer_vector <- c(1, 2, 3, 4, 5)
print(integer_vector)
In this code, we define a vector that contains the integers 1 through 5.
Accessing Elements in a Vector
You can access an element in a vector by its index. In R, indices start at 1. Here is how you can get the third element of our integer_vector
:
third_element <- integer_vector[3]
print(third_element)
This code will print 3
, which is the third element in our vector.
Vector Operations
R provides a variety of operations you can perform on vectors. For example, you can add two vectors together, and R will add the elements in each position together:
vector1 <- c(1, 2, 3)
vector2 <- c(4, 5, 6)
sum_vector <- vector1 + vector2
print(sum_vector)
This code will print 5 7 9
, which is the result of adding the two vectors together.
Lists
Lists are a special type of vector that can contain elements of different types.
Creating Lists
You can create a list in R using the list()
function. Here is an example of how to create a list:
my_list <- list("Red", 2, TRUE)
print(my_list)
In this code, we define a list that contains a string, an integer, and a boolean.
Accessing Elements in a List
You can access an element in a list by its index, just like in a vector. Here is how you can get the first element of our my_list
:
first_element <- my_list[1]
print(first_element)
This code will print "Red"
, which is the first element in our list.
List Operations
You can also perform operations on lists. For example, you can append an element to a list using the append()
function:
my_list <- append(my_list, "New Element")
print(my_list)
This code will add the string "New Element"
to the end of our list.
Conclusion
Vectors are a powerful data structure in R that allow you to store and manipulate collections of data. Whether you're working with atomic vectors of a single type or lists of multiple types, understanding how to create, access, and manipulate vectors is key to becoming proficient in R.