Blog

  • Replace the Elements of a Vector in R Programming – replace() Function

    replace() Function in detail

    The replace() function in R is used to replace specific values in a given vector at specified indices with new values.

    Syntax:

    replace(x, list, values)

    Parameters:

    • x: The input vector.
    • list: Indices where values need to be replaced.
    • values: New values that will replace the existing ones at the specified indices.

    Example 1:

    # R program to demonstrate
    # replace function
    
    # Initializing a vector
    data <- c("Apple", "Banana", "Cherry")
    
    # Display the original vector
    data
    
    # Replace the element at index 2 with "Blueberry"
    updated_data <- replace(data, 2, "Blueberry")
    
    # Display the updated vector
    updated_data

    Output:

    [1] "Apple"   "Banana"   "Cherry"
    [1] "Apple"   "Blueberry"   "Cherry"

    Example 2:

    # R program to demonstrate
    # replace function
    
    # Initializing a vector
    data <- c("Red", "Green", "Blue")
    
    # Display the original vector
    data
    
    # Replace the element at index 1 with "Yellow"
    # and the element at index 3 with "Orange"
    updated_data <- replace(data, c(1, 3), c("Yellow", "Orange"))
    
    # Display the updated vector
    updated_data

    Output:

    [1] "Red"   "Green"   "Blue"
    [1] "Yellow"   "Green"   "Orange"
  • Formatting Numbers and Strings in R Programming – format() Function

    Formatting Numbers and Strings in detail

    The format() function in R is a versatile tool that allows us to convert various objects, such as character strings, date/time data, and numeric values, into specific representations. By providing a wide range of formatting options, the function helps us control the appearance of the output.

    Using the format() function, we can customize numerical formatting by specifying parameters such as the number of decimal places (nsmall), the thousands separator (big.mark), the decimal mark (decimal.mark), and other relevant settings. Similarly, it enables the formatting of strings to follow a specific locale or meet particular presentation requirements.

    Syntax:

    format(x, digits, nsmall, scientific, width, justify = c("left", "right", "center", "none"))

    Parameters:

    • x: Input vector.
    • digits: Total number of digits to be displayed.
    • nsmall: Minimum number of digits to the right of the decimal point.
    • scientific: Set to TRUE to use scientific notation.
    • width: Minimum width of the output, with blank spaces padded at the beginning.
    • justify: Align the string output to the left, right, or center.
    String Formatting in R

    Example: String Placement with format()

    # Align string to the left
    output1 <- format("Data", width = 10, justify = "l")
    
    # Align string to the center
    output2 <- format("Data", width = 10, justify = "c")
    
    # Align string to the right
    output3 <- format("Data", width = 10, justify = "r")
    
    # Displaying the results
    print(output1)
    print(output2)
    print(output3)

    Output:

    [1] "Data      "
    [1] "   Data   "
    [1] "      Data"
    Number Formatting in R

    Example 1: Formatting Numbers with format()

    # Illustrating the format function
    
    # Rounding off numbers to specific digits
    num1 <- format(15.6789012, digits = 5)
    num2 <- format(15.6789012, digits = 7)
    print(num1)
    print(num2)
    
    # Specifying minimum digits after the decimal
    num3 <- format(15.6789012, nsmall = 3)
    num4 <- format(15.6789012, nsmall = 8)
    print(num3)
    print(num4)

    Output:

    [1] "15.679"
    [1] "15.67890"
    [1] "15.679"
    [1] "15.67890120"

    Example 2: Scientific Notation and String Representation

    # Convert numbers to strings
    str1 <- format(6789)
    str2 <- format(45.6789)
    print(str1)
    print(str2)
    
    # Displaying numbers in scientific notation
    sci1 <- format(45.6789, scientific = TRUE)
    sci2 <- format(45.6789, scientific = FALSE)
    print(sci1)
    print(sci2)

    Output:

    [1] "6789"
    [1] "45.6789"
    [1] "4.56789e+01"
    [1] "45.6789"
    Date and Time Formatting in R

    The format() function can also handle date and time objects, allowing custom string representations to be created.

    Example 1: Current Date and Time

    # Getting current date and time
    current_time <- Sys.time()
    
    # Formatting date-time in "YYYY-MM-DD HH:MM:SS" format
    formatted_time <- format(current_time, format = "%Y-%m-%d %H:%M:%S")
    print(formatted_time)

    Output:

    [1] "2025-01-28 15:45:00"

    Example 2: Date Formatting with Month Name

    # Formatting date with the month's name
    specific_date <- as.Date("2024-11-15")
    formatted_date <- format(specific_date, format = "%B %d, %Y")
    print(formatted_date)

    Output:

    [1] "November 15, 2024"
    • %Y: Year with century (e.g., 2024).
    • %B: Full month name (e.g., November).
    • %d: Day of the month (e.g., 15).
  • Get the Minimum and Maximum element of a Vector in R Programming – range() Function

    Get the Minimum and Maximum element of a Vector in R Programming in detail

    The range() function in R is used to determine the smallest (minimum) and largest (maximum) values in a given vector.

    Syntax:

    range(x, na.rm = FALSE, finite = FALSE)

    Parameters

    • x: A numeric vector whose minimum and maximum values are to be calculated.
    • na.rm: Logical (Boolean) value indicating whether to exclude NA values from the computation. Default is FALSE.
    • finite: Logical value to specify whether to exclude non-finite elements (like Inf and -Inf). Default is FALSE.

    Examples of range() Function in R

    Example 1: Finding the Minimum and Maximum of a Numeric Vector

    # Define a numeric vector
    vec <- c(10, 4, 7, 15, 2, 6)
    
    # Compute the range
    range(vec)

    Output:

    [1]  2 15

    Example 2: Handling NA and Non-Finite Values

    # Define a numeric vector with NA and non-finite values
    vec <- c(10, 4, NA, Inf, 7, -Inf, 2)
    
    # Compute the range without additional arguments
    range(vec)
    
    # Compute the range, ignoring NA values
    range(vec, na.rm = TRUE)
    
    # Compute the range, ignoring NA and non-finite values
    range(vec, na.rm = TRUE, finite = TRUE)

    Output:

    [1] NA NA
    [1]  -Inf   Inf
    [1]  2 10
  • Creating a Vector of sequenced elements in R Programming – seq() Function

    Creating a Vector of sequenced elements in detail

    Sequenced elements refer to items arranged in a specific order, one after the other. This concept is commonly applied in various fields to organize data systematically.

    seq() Function: The seq() function in R Programming Language is used to generate a sequence of elements in a vector. This function allows customization of the sequence using optional arguments such as the starting point, ending point, step size, and desired length of the vector.

    Syntax:

    seq(from, to, by, length.out)

    Parameters:

    • from: Starting value of the sequence
    • to: Ending value of the sequence
    • by: Step size or the difference between consecutive elements
    • length.out: Desired length of the sequence
    Creating a Vector of Sequenced Elements using seq() Function

    1. Basic Sequence Creation

    # Create a sequence of elements
    sequence <- seq(1, 5)
    sequence

    Output:

    [1] 1 2 3 4 5

    2. Using by Argument

    # Creating a vector with specified step size
    sequence_by <- seq(2, 12, by = 3)
    sequence_by

    Output:

    [1]  2  5  8 11

    3. Using from and to Arguments

    # Creating a sequence using from and to arguments
    sequence_from_to <- seq(from = 15, to = 20)
    sequence_from_to
    
    sequence_from_to
    # Creating a sequence using from and to arguments
    sequence_from_to <- seq(from = 15, to = 20)
    sequence_from_to

    Output:

    [1] 15 16 17 18 19 20

    4. Using length.out Argument

    # Creating a sequence with specified length
    sequence_length_out <- seq(from = 5, to = 15, length.out = 4)
    sequence_length_out

    Output:

    [1]  5.00  8.33 11.67 15.00

  • Length of Vectors – length() Function

    The length() function in R is a versatile tool used to determine or set the number of elements in a vector, list, or other objects. Vectors can be of various types such as numeric, character, or logical.

    Getting the Length of an Object

    To get the length of a vector or object, you can use the length() function.

    Syntax:

    length(x)

    Parameters:

    • x: A vector or an object whose length you want to determine.

    Example 1: Getting the Length of a Vector

    # R program to illustrate length function
    
    # Defining some vectors
    a <- c(10)
    b <- c(5, 8, 12, 15, 20)
    
    # Using length() function
    length(a)
    length(b)

    Output:

    [1] 1
    [1] 5

    Example 2: Getting the Length of a Matrix

    # Defining a matrix
    matrix_obj <- matrix(
        # A sequence of numbers
        c(1, 2, 3, 4, 5, 6),
    
        # Number of rows
        nrow = 2,
    
        # Number of columns
        ncol = 3
    )
    
    print(matrix_obj)
    
    # Finding the length of the matrix
    length(matrix_obj)

    Output:

    [,1] [,2] [,3]
    [1,]    1    3    5
    [2,]    2    4    6
    
    [1] 6

    Example 3: Getting the Length of a Data Frame

    # Defining a data frame
    data <- data.frame(
        Age = c(25, 30, 35, 40, 45),
        Salary = c(50000, 60000, 70000, 80000, 90000)
    )
    
    print(data)
    
    # Using length() function
    length(data)

    Output:

    Age Salary
    1  25  50000
    2  30  60000
    3  35  70000
    4  40  80000
    5  45  90000
    
    [1] 2

    Example 3:

    # Creating a vector with mismatched intervals
    incomplete_sequence = 2.1:6.9
    
    # Printing the vector
    print(incomplete_sequence)

    Output:

    [1] 2.1 3.1 4.1 5.1 6.1

    Note: For a data frame, length() returns the number of columns (variables).

    Example 4: Getting the Length of a List

    # Creating a list
    studentList <- list(
        StudentID = c(101, 102, 103),
        Names = c("Alice", "Bob", "Charlie"),
        Marks = c(89, 95, 78)
    )
    
    print(studentList)
    
    # Finding the length of the list
    length(studentList)

    Output:

    $StudentID
    [1] 101 102 103
    
    $Names
    [1] "Alice"   "Bob"     "Charlie"
    
    $Marks
    [1] 89 95 78
    
    [1] 3

    Example 5: Getting the Length of a String

    In R, determining the length of a string requires splitting it into individual characters first.

    # Defining a string
    text <- "Learning R Programming"
    
    # Basic application of length()
    length(text)
    
    # Splitting the string and counting characters
    length(unlist(strsplit(text, "")))

    Output:

    [1] 1
    [1] 22

    Setting the Length of a Vector

    You can also set the length of a vector using the length() function.

    Syntax:

    length(x) <- value

    Parameters:

    • x: A vector or object.
    • value: The desired length of the vector.

    Example:

    # Defining some vectors
    p <- c(7)
    q <- c(10, 20, 30, 40)
    r <- c(1, 3, 5, 7, 9)
    
    # Setting new lengths for the vectors
    length(p) <- 3
    length(q) <- 6
    length(r) <- 4
    
    # Displaying the modified vectors
    p
    q
    r

    Output:

    [1]  7 NA NA
    [1] 10 20 30 40 NA NA
    [1] 1 3 5 7
  • Assigning Vectors in R Programming

    Assigning Vectors in detail

    Vectors are one of the fundamental data structures in R. They store data of the same type and are equivalent to arrays in many other programming languages. In R, an array is essentially a vector with one or more dimensions, and almost every object created in R is stored as a vector. The elements of a vector are referred to as its components.

    Assigning Vectors

    There are multiple ways to assign values to vectors in R. This can be achieved using the c() function, the : operator, or the seq() function.

    Assigning Vectors Using c():

    The c() function is commonly used to create vectors in R.

    Example 1:

    # Creating a vector using c()
    numbers = c(10, 20, 30, 40, 50)
    
    # Printing the vector
    print(numbers)
    
    # Printing the data type of the vector
    print(typeof(numbers))

    Output:

    [1] 10 20 30 40 50
    [1] "double"

    Example 2:

    # Creating a mixed vector
    mixed_vector = c(3.2, FALSE, 8, "LearnR")
    
    # Printing the vector
    print(mixed_vector)
    
    # Printing the data type of the vector
    print(typeof(mixed_vector))

    Output:

    [1] "3.2"    "FALSE"  "8"      "LearnR"
    [1] "character"

    Assigning Vectors Using :

    The : operator is used to create vectors of consecutive values.

    Example 1:

    # Creating a vector of consecutive integers
    sequence = 5:15
    
    # Printing the vector
    print(sequence)

    Output:

    [1]  5  6  7  8  9 10 11 12 13 14 15

    Example 2:

    # Creating a vector of consecutive decimal numbers
    decimal_sequence = 2.1:6.1
    
    # Printing the vector
    print(decimal_sequence)

    Output:

    [1] 2.1 3.1 4.1 5.1 6.1

    Example 3:

    # Creating a vector with mismatched intervals
    incomplete_sequence = 2.1:6.9
    
    # Printing the vector
    print(incomplete_sequence)

    Output:

    [1] 2.1 3.1 4.1 5.1 6.1

    Assigning Vectors Using seq()

    The seq() function allows the creation of vectors with custom step sizes.

    Example 1:

    # Creating a vector using seq() with a custom step size
    stepped_vector = seq(2, 10, by = 1.5)
    
    # Printing the vector
    print(stepped_vector)

    Output:

    [1] 2.0 3.5 5.0 6.5 8.0 9.5

    Example 2:

    You can also specify the desired length of the vector, and R will calculate the step size automatically.

    # Creating a vector with a specified length
    length_based_vector = seq(1, 20, length.out = 5)
    
    # Printing the vector
    print(length_based_vector)

    Output:

    [1]  1.00  5.75 10.50 15.25 20.00
    Assigning Named Vectors in R

    R allows the creation of named vectors where each value is associated with a specific name. The names() function can be used for this purpose.

    Example:

    Suppose we want to create a vector representing the number of team members in different departments.

    # Creating a numeric vector for team sizes
    team_sizes = c(4, 6, 10, 12)
    
    # Assigning department names
    names(team_sizes) = c("HR", "Finance", "Development", "Operations")
    
    # Displaying the named vector
    print(team_sizes)

    Output:

    HR     Finance Development  Operations
    4           6          10          12

    To access a department with a specific team size:

    # Displaying the department with 10 team members
    print(names(team_sizes[team_sizes == 10]))
    
    # Displaying the department with 3 team members
    print(names(team_sizes[team_sizes == 3]))

    Output:

    [1] "Development"
    character(0)
    Accessing Elements of a Vector

    Vector indexing in R is used to access individual elements or subsets of a vector. Note that indexing in R starts from 1, not 0.

    Example 1:

    # Creating a vector using seq()
    values = seq(10, 100, by = 10)
    
    # Printing the vector
    print(values)
    
    # Accessing the fourth element
    print(values[4])

    Output:

    [1] 10 20 30 40 50 60 70 80 90 100
    [1] 40

    Example 2:

    # Accessing multiple elements
    print(values[c(2, 5, 8)])

    Output:

    [1] 20 50 80
  • Types of Vectors in R Programming

    Types of Vectors in detail

    Vectors in R programming are similar to arrays in C language and are used to hold multiple data values of the same type. One key difference is that in R, the indexing of vectors starts from 1 instead of 0. Vectors are the most fundamental data types in R. Even a single object is stored in the form of a vector. Vectors are essentially arrays and contain a sequence of homogeneous data types.

    There are two main types of vectors in R:

    1. Atomic Vector
      1. Integer
      2. Double
      3. Logical
      4. Character
      5. Complex
      6. Raw
    2. Recursive Vector
      • List

    The primary difference between atomic vectors and recursive vectors (lists) is that atomic vectors are homogeneous, while recursive vectors (lists) can be heterogeneous.

    Vectors in R have three common properties:

    • Type: What it is, determined using the typeof() function.
    • Length: Number of elements it contains, determined using the length() function.
    • Attributes: Additional metadata, accessed using the attributes() function.
    1. Atomic Vectors

    i. Integer Vector

    Integer vectors store whole numbers (positive or negative). In R, numbers are double by default, so to explicitly create an integer, append L after the number.

    Example:

    # Creating an integer vector
    v1 <- c(10L, -3L, 7L, 22L)
    
    # Printing the vector
    print(v1)
    
    # Displaying the type of vector
    print(typeof(v1))

    Output:

    [1] 10 -3  7 22
    [1] "integer"

    ii. Double Vector: Double vectors include numbers with decimal values. In R, numbers are double by default.

    Example:

    # Creating a double vector
    v1 <- c(3.14, 5.67, -2.18, 0.99)
    
    # Printing the vector
    print(v1)
    
    # Displaying the type of vector
    print(typeof(v1))

    Output:

    [1]  3.14  5.67 -2.18  0.99
    [1] "double"

    iii. Logical Vector: Logical vectors can have three possible values: TRUEFALSE, and NA. They are often created using comparison operators or the c() function.

    Example:

    # Creating a logical vector
    v1 <- c(TRUE, FALSE, TRUE, NA)
    
    # Printing the vector
    print(v1)
    
    # Displaying the type of vector
    print(typeof(v1))

    Output:

    [1]  TRUE FALSE  TRUE    NA
    [1] "logical"

    iv Character Vector: Character vectors store strings. Each element of a character vector is a string, which can include alphabets, numbers, and symbols. Values are represented in quotes.

    Example:

    # Creating a character vector
    v1 <- c("apple", "42", "hello", "99.9")
    
    # Printing the vector
    print(v1)
    
    # Displaying the type of vector
    print(typeof(v1))

    Output:

    [1] "apple" "42"    "hello" "99.9"
    [1] "character"

    v. Complex Vector: Complex vectors store numbers with an imaginary component. Examples include 3+4i or -7i.

    Example:

    # Creating a complex vector
    v1 <- c(2+3i, -1-2i, 0+4i, 7-3i)
    
    # Printing the vector
    print(v1)
    
    # Displaying the type of vector
    print(typeof(v1))

    Output:

    [1]  2+3i -1-2i  0+4i  7-3i
    [1] "complex"

    vi. Raw Vector: Raw vectors store raw bytes of data and can be created using the raw() function.

    Example:

    [1] "1" "2" "3" "a" "b" "c"

    Output:

    [1] 00 00 00 00
    [1] "raw"
    2. Recursive Vector (List)

    Lists are more flexible than atomic vectors because they can hold elements of different types, including other lists. Lists are often used to represent hierarchical or tree-like data structures.

    Example:

    # Creating a list (recursive vector)
    l1 <- list("text", 42, TRUE, c(3, 4, 5))
    
    # Printing the list
    print(l1)
    
    # Displaying the type of the list
    print(typeof(l1))

    Output:

    [[1]]
    [1] "text"
    
    [[2]]
    [1] 42
    
    [[3]]
    [1] TRUE
    
    [[4]]
    [1] 3 4 5
    
    [1] "list"
  • Dot Product of Vectors in R Programming

    Dot Product of Vectors in detail

    Vectors are the fundamental data types in R. Any object created is stored as a vector by default. A vector is essentially a sequence of homogeneous data elements, similar to arrays in other programming languages. When a vector contains mixed data types, R automatically converts the elements to the type with the highest precedence.

    Numerous operations can be performed on vectors in R, such as creation, access, modification, deletion, arithmetic operations, and sorting.

    What is an Append Operation in R?

    A vector in R is a basic object that contains sequences of elements of the same type. It can hold values such as integers, characters, logicals, doubles, etc. You can append new values to an existing vector using three primary methods:

    1. Using the c() function
    2. Using the append() function
    3. Using indexing
    1. Append Operation Using c() Function

    The c() function is a generic function that combines multiple objects into a single vector or list.

    Syntax:

    c(...)

    Parameters:

    ...: The objects or values to be concatenated.

    To explore additional options, run:

    help("c")

    Example 1: Basic Append with c()

    # Create vectors
    nums <- 10:14
    extra_nums <- 15:18
    
    # Append using c()
    result <- c(nums, extra_nums)
    
    # Print result
    print(result)

    Output:

    [1] 10 11 12 13 14 15 16 17 18

    Example 2: Append with Mixed Types

    # Create vectors
    nums <- 1:4
    chars <- c("x", "y", "z")
    
    # Append using c()
    combined <- c(nums, chars)
    
    # Print result
    print(combined)
    
    # Check types
    print(typeof(combined))
    print(typeof(nums))
    print(typeof(chars))

    Output:

    [1] "1" "2" "3" "4" "x" "y" "z"
    [1] "character"
    [1] "integer"
    [1] "character"
    2. Append Operation Using append() Function

    The append() function is specifically designed to merge vectors or add elements to a vector.

    Syntax:

    append(x, values)

    Parameters:

    • x: The vector to which elements are appended.
    • values: The values to append to the vector.

    Example 3: Append with append() Function

    # Create a vector
    vec <- c(20, 30, 40)
    
    # Append values
    vec <- append(vec, c(50, 60))
    
    # Print result
    print(vec)

    Output:

    [1] 20 30 40 50 60

    Example 4: Append Mixed Types with append()

    # Create vectors
    nums <- c(1, 2, 3)
    letters <- c("a", "b", "c")
    
    # Append characters to numeric vector
    combined <- append(nums, letters)
    
    # Print result
    print(combined)

    Output:

    [1] "1" "2" "3" "a" "b" "c"
    3. Append Operation Using Indexing

    You can also add elements to a vector by directly assigning values to positions beyond its current length.

    Example 5: Append Using Indexing

    # Create a vector
    my_vector <- c(5, 10, 15)
    
    # Append values using indexing
    my_vector[4] <- 20
    my_vector[5] <- 25
    
    # Print result
    print(my_vector)

    Output:

    [1]  5 10 15 20 25
  • Append Operation on Vectors in R Programming

    Append Operation on Vectors in detail

    Vectors are the fundamental data types in R. Any object created is stored as a vector by default. A vector is essentially a sequence of homogeneous data elements, similar to arrays in other programming languages. When a vector contains mixed data types, R automatically converts the elements to the type with the highest precedence.

    Numerous operations can be performed on vectors in R, such as creation, access, modification, deletion, arithmetic operations, and sorting.

    What is an Append Operation in R?

    A vector in R is a basic object that contains sequences of elements of the same type. It can hold values such as integers, characters, logicals, doubles, etc. You can append new values to an existing vector using three primary methods:

    1. Using the c() function
    2. Using the append() function
    3. Using indexing
    1. Append Operation Using c() Function

    The c() function is a generic function that combines multiple objects into a single vector or list.

    Syntax:

    c(...)

    Parameters:

    ...: The objects or values to be concatenated.

    To explore additional options, run:

    help("c")

    Example 1: Basic Append with c()

    # Create vectors
    nums <- 10:14
    extra_nums <- 15:18
    
    # Append using c()
    result <- c(nums, extra_nums)
    
    # Print result
    print(result)

    Output:

    [1] 10 11 12 13 14 15 16 17 18

    Example 2: Append with Mixed Types

    # Create vectors
    nums <- 1:4
    chars <- c("x", "y", "z")
    
    # Append using c()
    combined <- c(nums, chars)
    
    # Print result
    print(combined)
    
    # Check types
    print(typeof(combined))
    print(typeof(nums))
    print(typeof(chars))

    Output:

    [1] "1" "2" "3" "4" "x" "y" "z"
    [1] "character"
    [1] "integer"
    [1] "character"
    2. Append Operation Using append() Function

    The append() function is specifically designed to merge vectors or add elements to a vector.

    Syntax:

    append(x, values)

    Parameters:

    • x: The vector to which elements are appended.
    • values: The values to append to the vector.

    Example 3: Append with append() Function

    # Create a vector
    vec <- c(20, 30, 40)
    
    # Append values
    vec <- append(vec, c(50, 60))
    
    # Print result
    print(vec)

    Output:

    [1] 20 30 40 50 60

    Example 4: Append Mixed Types with append()

    # Create vectors
    nums <- c(1, 2, 3)
    letters <- c("a", "b", "c")
    
    # Append characters to numeric vector
    combined <- append(nums, letters)
    
    # Print result
    print(combined)

    Output:

    [1] "1" "2" "3" "a" "b" "c"
    3. Append Operation Using Indexing

    You can also add elements to a vector by directly assigning values to positions beyond its current length.

    Example 5: Append Using Indexing

    # Create a vector
    my_vector <- c(5, 10, 15)
    
    # Append values using indexing
    my_vector[4] <- 20
    my_vector[5] <- 25
    
    # Print result
    print(my_vector)

    Output:

    [1]  5 10 15 20 25
  • Operations on Vectors in R

    Operations in detail

    Vectors are the fundamental data types in R. Any object created is stored as a vector by default. A vector is essentially a sequence of homogeneous data elements, similar to arrays in other programming languages. When a vector contains mixed data types, R automatically converts the elements to the type with the highest precedence.

    Numerous operations can be performed on vectors in R, such as creation, access, modification, deletion, arithmetic operations, and sorting.

    Creating a Vector

    Vectors can be created in several ways, the most common being the c() function, which combines elements into a vector.

    # Using 'c()' to combine values into a vector
    # The type defaults to double
    vec1 <- c(3, 8, 1, 9, 4)
    print('Vector using c():')
    print(vec1)
    
    # Using seq() to create a sequence with specified step size and length
    vec2 <- seq(2, 12, length.out = 4)
    print('Vector using seq():')
    print(vec2)
    
    # Using ':' operator for continuous sequences
    vec3 <- 10:15
    print('Vector using colon:')
    print(vec3)
    Accessing Vector Elements

    In R, vector elements are accessed using square brackets []. R follows a 1-based indexing system, unlike programming languages like C or Python where indexing starts from 0.

    # Accessing elements using position
    vec1 <- c(5, 9, 2, 6, 3)
    print('Accessing second element:')
    print(vec1[2])
    
    # Accessing specific elements using another vector
    vec2 <- c(4, 7, 1, 8, 5)
    print('Accessing specific elements:')
    print(vec2[c(1, 4)])
    
    # Logical indexing to filter elements
    vec3 <- c(6, 2, 8, 3, 7)
    print('Elements greater than 5:')
    print(vec3[vec3 > 5])

    Output:

    Accessing second element:
    [1] 9
    Accessing specific elements:
    [1] 4 8
    Elements greater than 5:
    [1] 6 8 7
    Modifying a Vector

    Vectors can be modified using indexing or logical operations.

    # Creating a vector
    vec <- c(4, 7, 1, 9, 3)
    
    # Modifying a specific element
    vec[3] <- 10
    print('Modified third element:')
    print(vec)
    
    # Logical indexing to modify elements
    vec[vec > 8] <- 0
    print('Replaced elements greater than 8:')
    print(vec)
    
    # Rearranging the vector using positions
    vec <- vec[c(5, 1, 2)]
    print('Rearranged vector:')
    print(vec)

    Output:

    Modified third element:
    [1]  4  7 10  9  3
    Replaced elements greater than 8:
    [1]  4  7 10  0  3
    Rearranged vector:
    [1]  3  4  7
    Deleting a Vector

    To delete a vector, it can be reassigned to NULL.

    # Creating a vector
    vec <- c(3, 6, 1, 8)
    
    # Deleting the vector
    vec <- NULL
    print('Deleted vector:')
    print(vec)

    Output:

    Deleted vector:
    NULL
    Arithmetic Operations

    Arithmetic operations on vectors are performed element-wise. Both vectors should have the same length.

    # Creating two vectors
    vec1 <- c(6, 3, 9, 1, 7)
    vec2 <- c(2, 5, 4, 8, 3)
    
    # Addition
    add <- vec1 + vec2
    print('Addition:')
    print(add)
    
    # Subtraction
    sub <- vec1 - vec2
    print('Subtraction:')
    print(sub)
    
    # Multiplication
    mul <- vec1 * vec2
    print('Multiplication:')
    print(mul)
    
    # Division
    div <- vec1 / vec2
    print('Division:')
    print(div)

    Output:

    Addition:
    [1]  8  8 13  9 10
    Subtraction:
    [1]  4 -2  5 -7  4
    Multiplication:
    [1] 12 15 36  8 21
    Division:
    [1] 3.000000 0.600000 2.250000 0.125000 2.333333
    Sorting a Vector

    The sort() function is used to arrange vector elements. By default, sorting is done in ascending order.

    # Creating a vector
    vec <- c(9, 3, 7, 1, 8, 2)
    
    # Sorting in ascending order
    asc <- sort(vec)
    print('Ascending order:')
    print(asc)
    
    # Sorting in descending order
    desc <- sort(vec, decreasing = TRUE)
    print('Descending order:')
    print(desc)

    Output:

    Ascending order:
    [1] 1 2 3 7 8 9
    Descending order:
    [1] 9 8 7 3 2 1