R Tutorial

# Vectors in R

Vectors are fundamental data structures in R that store a sequence of values of the same data type. They provide a versatile way to handle and manipulate data, serving as the building blocks for more complex data structures. Here's an explanation of vectors in R with examples:

## Creating Vectors

You can create a vector in R using the c() function, which combines elements into a single vector.

Creating Numeric Vector
numeric_vector <- c(1, 2, 3, 4, 5)
Creating Character Vector
character_vector <- c("red", "green", "blue")
Creating Logical Vector
logical_vector <- c(TRUE, FALSE, TRUE)

## seq() function

Vectors can also be created using the seq() function. The seq() function takes a start value, an end value, and an increment as its arguments. The seq() function returns a vector of numbers that starts at the start value, increments by the increment, and ends at the end value. For example, the following code creates a vector of numbers from 1 to 10:

vector_of_numbers <- seq(1, 10)

The vector_of_numbers vector now contains the numbers 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10.

## Vector Operations

Vectors support various operations, including element-wise arithmetic, logical operations, and subsetting.

Arithmetic Operations
a <- c(1, 2, 3) b <- c(4, 5, 6) sum_vector <- a + b # Element-wise addition print(sum_vector) #Output:5 7 9
Logical Operations
c <- c(TRUE, TRUE, FALSE) d <- c(FALSE, TRUE, TRUE) logical_result <- c & d # Element-wise AND operation print(logical_result) #Output:FALSE TRUE FALSE
Indexing and Subsetting

You can access specific elements of a vector using indexing.

colors <- c("red", "green", "blue", "yellow") third_color <- colors[3] # Accessing the third element ("blue") print(third_color) #Output:"blue"

## Vector Functions

R provides functions to perform operations on vectors.

numbers <- c(10, 20, 30, 40) sum_value <- sum(numbers) # Sum of all elements (100) mean_value <- mean(numbers) # Mean of all elements (25) print(sum_value) print(mean_value) #Output: 100 25

## Slicing a Vector

Vectors can also be sliced. Slicing a vector returns a new vector that contains a subset of the elements of the original vector. For example, the following code slices the vector_of_numbers vector to return the first three elements:

sliced_vector <- vector_of_numbers[1:3]

The sliced_vector vector now contains the numbers 1, 2, and 3.

### Conclusion

Vectors are a cornerstone of R programming, allowing you to efficiently work with and manipulate data. They are used extensively in mathematical operations, data analysis, and other programming tasks. Understanding vectors is essential for effectively utilizing R's capabilities for various types of data processing.