In this tutorial, we will explore the vector data structure in R. A vector is one of the most fundamental data structures in R and it plays a crucial role in data manipulation and analysis.

**What is a Vector?**

A vector is a one-dimensional array-like structure that can hold elements of the same data type. It is a fundamental building block in R and is used to store and manipulate data efficiently.

__Creating Vectors__

There are several ways to create vectors in R. One common method is to use the **c()** function, which stands for “combine” or “concatenate”. This function allows us to combine several values into a single vector.

Let’s take an example of creating a numeric vector:

my_vector <- c(1, 2, 3, 4, 5)

We can also create character vectors by enclosing the values in quotes:

my_vector <- c("apple", "banana", "orange")

__Accessing Elements in Vectors__

Once we have created a vector, we can access its elements using indexing. Indexing in R starts at 1 (unlike some other programming languages which start at 0).

To access individual elements of a vector, we can use square brackets [] with the index number inside. For example:

my_vector <- c(1, 2, 3, 4, 5)# Accessing the first elementprint(my_vector[1]) # Output: 1# Accessing the third elementprint(my_vector[3]) # Output: 3

We can also access multiple elements at once by providing a sequence of indices inside square brackets:

# Accessing first three elementsprint(my_vector[1:3]) # Output: 1 2 3

__Vector Operations__

Vectors in R support various operations such as arithmetic operations, element-wise operations, and logical operations.

Arithmetic operations can be performed on numeric vectors:

# Adding two vectorsvector1 <- c(1, 2, 3) vector2 <- c(4, 5, 6) result <- vector1 + vector2 print(result) # Output: 5 7 9

Element-wise operations are performed on each element of the vector:

# Squaring each element of a vectormy_vector <- c(1, 2, 3) result <- my_vector^2 print(result) # Output: 1 4 9

Logical operations can be used to compare vectors element-wise:

# Comparing two vectors element-wisevector1 <- c(1, 2, 3) vector2 <- c(4, 5, 6) result <- vector1 > vector2 print(result) # Output: FALSE FALSE FALSE

__Summary__

In this tutorial, we learned about the vector data structure in R. We explored how to create vectors using the **c()** function and accessed individual elements using indexing. We also discussed various operations that can be performed on vectors.

Vectors are an essential tool for data manipulation and analysis in R. Understanding their properties and functionalities will help you effectively work with data in R.