Vectors in R Programming


1. Creating Vectors

Vectors are one-dimensional arrays that can hold numeric, character, or logical data.

    # Creating a numeric vector
    numeric_vector <- c(1, 2, 3, 4, 5)
    print(numeric_vector)
    
    # Creating a character vector
    character_vector <- c("apple", "banana", "cherry")
    print(character_vector)
    
    # Creating a logical vector
    logical_vector <- c(TRUE, FALSE, TRUE)
    print(logical_vector)
        

2. Indexing Vectors

Elements in a vector can be accessed using their index positions. Indexing in R starts from 1.

    # Accessing elements
    numeric_vector <- c(10, 20, 30, 40, 50)
    
    # Access the first element
    print(numeric_vector[1])
    
    # Access multiple elements
    print(numeric_vector[c(1, 3, 5)])
    
    # Exclude specific elements
    print(numeric_vector[-2])
        

3. Manipulating Vectors

Vectors can be manipulated using arithmetic operations and built-in functions.

    # Arithmetic operations on vectors
    vector_a <- c(1, 2, 3)
    vector_b <- c(4, 5, 6)
    
    # Element-wise addition
    result_add <- vector_a + vector_b
    print(result_add)
    
    # Element-wise multiplication
    result_mul <- vector_a * vector_b
    print(result_mul)
    
    # Using built-in functions
    numeric_vector <- c(10, 20, 30, 40, 50)
    
    # Calculate the sum
    result_sum <- sum(numeric_vector)
    print(result_sum)
    
    # Calculate the mean
    result_mean <- mean(numeric_vector)
    print(result_mean)
        

4. Modifying Vector Elements

Elements of a vector can be modified by assigning new values to specific indices.

    # Modify vector elements
    numeric_vector <- c(1, 2, 3, 4, 5)
    
    # Change the second element
    numeric_vector[2] <- 20
    print(numeric_vector)
    
    # Change multiple elements
    numeric_vector[c(1, 3)] <- c(10, 30)
    print(numeric_vector)
        

Conclusion

This tutorial introduced vectors in R, including their creation, indexing, and manipulation. Vectors are a fundamental data type in R and are essential for data analysis and operations.





Advertisement