R Vectors

A basic data structure in R for storing a grouping of items of the same data type is called a vector. R vectors are one-dimensional arrays that are capable of storing a variety of elements, including characters, numbers, logical values, and more. In R, vectors can be created and worked with in the following common ways:

1, Creating Vectors:

a. Numeric Vectors:

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

b. Character Vectors:

character_vector <- c(“apple”, “banana”, “cherry”)

c. Logical Vectors:

logical_vector <- c(TRUE, FALSE, TRUE, TRUE)

d. Vector of a Single Type:

Vectors in R are homogeneous, meaning all elements must be of the same data type. If you mix types, R will implicitly convert them to a common type.

2. Accessing Elements:

You can access vector elements using indexing. Indexing in R starts from 1.

my_vector <- c(10, 20, 30, 40, 50)

element_3 <- my_vector[3]  # Access the third element (element_3 will be 30)

3. Vector Operations:

You can perform various operations on vectors, such as addition, subtraction, multiplication, and more. These operations are element-wise.

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

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

result <- vector1 + vector2  # Element-wise addition

4. Vector Functions:

R provides functions to work with vectors, such as length(), sum(), mean(), min(), max(), and more.

numbers <- c(5, 10, 15, 20, 25)

length_of_vector <- length(numbers)

sum_of_vector <- sum(numbers)

5. Vector Sequences:

You can create numeric vectors with sequences using seq() or :.

seq_vector <- seq(1, 10, by = 2)  # Creates a sequence from 1 to 10 with a step of 2

colon_vector <- 1:5  # Creates a sequence from 1 to 5

6. Vector Manipulation:

You can modify vectors by adding or removing elements.

my_vector <- c(10, 20, 30)

my_vector <- c(my_vector, 40)  # Append an element

my_vector <- my_vector[-2]  # Remove the second element

7. Named Vectors:

You can assign names to vector elements for better readability and indexing.

named_vector <- c(apple = 10, banana = 20, cherry = 30)

value <- named_vector[“banana”]  # Access “banana” element by name

These are the basics of working with vectors in R. Vectors are a fundamental building block in R, and they play a crucial role in many data analysis and statistical operations.

Leave a Comment

Your email address will not be published. Required fields are marked *