Vectors are a fundamental data structure in R. They are used to store a sequence of elements of the same type. Vectors can hold numbers, characters, or logical values.

Creating a vector is straightforward. You use the `c()` function to combine elements into a single vector. For example, `c(1, 2, 3)` creates a numeric vector with three elements.

Vectors support various operations and functions. You can access, modify, and perform calculations directly on them. This flexibility makes vectors essential for data manipulation and analysis in R.

### Creating Vectors

Vectors are a basic data type in R. They can be created using the `c()`

function.

# Create a numeric vector numeric_vector <- c(1, 2, 3, 4, 5) numeric_vector

Output:

[1] 1 2 3 4 5

### Creating Vectors of Different Types

Vectors can also hold characters or logical values.

# Create a character vector char_vector <- c("apple", "banana", "cherry") char_vector # Create a logical vector logical_vector <- c(TRUE, FALSE, TRUE) logical_vector

Output for character vector:

[1] "apple" "banana" "cherry"

Output for logical vector:

[1] TRUE FALSE TRUE

### Accessing Elements

You can access vector elements using square brackets.

# Access the second element numeric_vector[2]

Output:

[1] 2

### Modifying Elements

Change elements by assigning new values.

# Modify the third element numeric_vector[3] <- 10 numeric_vector

Output:

[1] 1 2 10 4 5

### Vector Operations

Perform operations directly on vectors.

# Add 5 to each element numeric_vector + 5

Output:

[1] 6 7 15 9 10

### Combining Vectors

Combine vectors with the `c()`

function.

# Combine two vectors combined_vector <- c(numeric_vector, char_vector) combined_vector

Output:

[1] "1" "2" "10" "4" "5" "apple" "banana" "cherry"

### Using Functions with Vectors

Apply functions like `length()`

and `mean()`

to vectors.

# Get the length of a vector length(numeric_vector) # Calculate the mean of a numeric vector mean(numeric_vector)

Output for length:

[1] 5

Output for mean:

[1] 6.2