Author: Pooja Kotwani

  • 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

  • Introduction to Vectors in R

    Vectors are the most fundamental data structure in R. Almost everything in R—numbers, characters, logical values, and even matrices—is built on top of vectors. Understanding vectors deeply is essential to mastering R programming, data analysis, and statistical computing.

    What is a Vector in R?

    A vector is a one-dimensional data structure that stores a sequence of elements of the same data type. All elements in a vector must belong to the same type; if different types are mixed, R automatically converts them to a common type (this process is called type coercion).

    Examples of vectors:

    • A list of numbers
    • A set of names
    • A sequence of TRUE/FALSE values

    Why Vectors are Important in R

    Vectors are important because:

    • R is a vectorized language
    • Operations on vectors are faster than loops
    • Most R functions expect vector inputs
    • Data frames and matrices are built from vectors

    R encourages vectorized operations, which means you can operate on an entire vector at once without using loops.

    Creating Vectors in R

    Creating a Vector Using c() Function

    The most common way to create a vector is using the c() (combine) function.

    numbers <- c(10, 20, 30, 40)
    names <- c("Alice", "Bob", "Charlie")
    logical_values <- c(TRUE, FALSE, TRUE)
    

    Creating an Empty Vector

    You can create an empty vector and fill it later.

    empty_vec <- c()
    

    Or create a vector of a specific type and length:

    numeric_vec <- numeric(5)
    character_vec <- character(3)
    logical_vec <- logical(4)
    

    Types of Vectors in R

    R supports atomic vectors, which include:

    Numeric Vector

    Stores decimal numbers.

    x <- c(1.5, 2.3, 4.7)
    

    Integer Vector

    Stores integers (use L).

    y <- c(1L, 2L, 3L)
    

    Character Vector

    Stores text strings.

    z <- c("R", "Data", "Science")
    

    Logical Vector

    Stores TRUE/FALSE values.

    flag <- c(TRUE, FALSE, TRUE)
    

    Complex Vector

    Stores complex numbers.

    cplx <- c(2+3i, 4+5i)
    

    Checking the Type of a Vector

    Use class() or typeof().

    class(numbers)
    typeof(numbers)
    

    Vector Type Coercion

    When different data types are combined in a vector, R automatically converts all elements to the most flexible type.

    Coercion Hierarchy

    logical → integer → numeric → character
    

    Example:

    mixed <- c(1, TRUE, "R")
    print(mixed)
    

    Output:

    [1] "1" "TRUE" "R"
    

    Vector Indexing

    Indexing is used to access elements in a vector.

    Indexing by Position

    R uses 1-based indexing.

    v <- c(10, 20, 30, 40)
    v[1]    # First element
    v[4]    # Fourth element
    

    Indexing with Multiple Positions

    v[c(1, 3)]
    

    Negative Indexing

    Negative indices remove elements.

    v[-2]
    

    Logical Indexing

    Logical vectors can be used to filter data.

    v[v > 20]
    

    Naming Vector Elements

    You can assign names to vector elements.

    scores <- c(85, 90, 78)
    names(scores) <- c("Math", "Science", "English")
    

    Access by name:

    scores["Math"]
    

    Vector Recycling Rule

    When performing operations on vectors of unequal length, R recycles the shorter vector.

    Example:

    v1 <- c(1, 2, 3, 4)
    v2 <- c(10, 20)
    v1 + v2
    

    R repeats v2:

    1+10, 2+20, 3+10, 4+20
    

    Warning is issued if lengths are not multiples.

    Vectorized Operations

    R allows operations on entire vectors without loops.

    v <- c(1, 2, 3, 4)
    v * 2
    v + 10
    

    This is faster and cleaner than using loops.

    Common Vector Functions

    Length of Vector

    length(v)
    

    Sorting a Vector

    sort(v)
    

    Finding Minimum and Maximum

    min(v)
    max(v)
    

    Sum and Mean

    sum(v)
    mean(v)
    

    Creating Sequences of Vectors

    Using :

    1:10
    

    Using seq()

    seq(from = 1, to = 10, by = 2)
    

    Using rep()

    rep(1:3, times = 2)
    

    Modifying Vectors

    Updating Elements

    v[2] <- 100
    

    Replacing Based on Condition

    v[v < 10] <- 0
    

    Removing Elements from a Vector

    v <- v[-3]
    

    Checking Membership

    Use %in% to check if elements exist.

    5 %in% v
    

    Practical Example

    marks <- c(45, 67, 89, 90, 34)
    passed <- marks[marks >= 40]
    average <- mean(passed)
    
    print(passed)
    print(average)
    

    Common Mistakes with Vectors

    • Mixing data types unintentionally
    • Forgetting R uses 1-based indexing
    • Ignoring recycling warnings
    • Using loops instead of vectorized operations

    Summary

    Vectors are the backbone of R programming. They store data in a one-dimensional format and support fast, vectorized operations. Understanding how to create, index, modify, and operate on vectors is crucial for working with data frames, matrices, and advanced statistical functions in R.

  • Data Structures

    data structure is a specific way of organizing and storing data in a computer so that it can be used efficiently. The goal is to optimize time and space complexity for various tasks. In R programming, data structures are tools designed to handle and manipulate collections of values.

    R’s native data structures are often categorized based on their dimensionality (1D, 2D, or nD) and whether they are homogeneous (all elements must be of the same type) or heterogeneous (elements can have different types). This classification results in six commonly used data structures for data analysis in R.

    The most essential data structures used in R include: 

    1. Vectors
    2. Lists
    3. Dataframes
    4. Matrices
    5. Arrays
    6. Factors
    7. Tibbles

    R Vectors

    Vectors in R are analogous to arrays in other programming languages and are used to store multiple values of the same type. A key difference is that R uses 1-based indexing (indexing starts at 1, not 0). Vectors can hold numeric, character, or logical values.

    Creating a Vector

    A vector is a fundamental data structure in R, representing a one-dimensional array. The c() function is the most common method for creating a vector.

    # R program to create Vectors
    
    # Using c() function to create a numeric vector
    A <- c(10, 20, 30, 40)
    cat('Using c() function:', A, '\n')
    
    # Using seq() function for generating a sequence
    # length.out defines the number of values in the sequence
    B <- seq(5, 25, length.out = 6)
    cat('Using seq() function:', B, '\n')
    
    # Using colon (:) to create a sequence
    C <- 3:9
    cat('Using colon operator:', C)

    Output:

    Using c() function: 10 20 30 40
    Using seq() function: 5 9 13 17 21 25
    Using colon operator: 3 4 5 6 7 8 9
    Types of R Vectors

    Numeric Vectors: Numeric vectors store numbers, which can be integers or doubles.

    # R program to create Numeric Vectors
    
    # Creating a vector using c()
    num1 <- c(1.5, 2.5, 3.5)
    
    # Display type of vector
    typeof(num1)
    
    # Using L to specify integers
    num2 <- c(10L, 20L, 30L)
    typeof(num2)

    Output:

    [1] "double"
    [1] "integer"

    Character Vectors: Character vectors store strings and can also include numbers treated as characters.

    # R program to create Character Vectors
    
    # Creating a character vector
    charVec <- c("apple", "orange", "42", "75")
    typeof(charVec)

    Output:

    [1] "character"

    Logical Vectors: Logical vectors store Boolean values (TRUEFALSE, or NA).

    # R program to create Logical Vectors
    
    # Creating a logical vector
    logVec <- c(TRUE, FALSE, TRUE, NA)
    typeof(logVec)

    Output:

    [1] "logical"
    Length of a Vector

    The length of a vector is the count of its elements. Use the length() function to find it.

    # R program to find vector lengths
    
    # Numeric vector
    numVec <- c(3, 6, 9, 12)
    length(numVec)
    
    # Character vector
    charVec <- c("car", "bike", "train")
    length(charVec)
    
    # Logical vector
    logVec <- c(TRUE, TRUE, FALSE, NA)
    length(logVec)

    Output:

    [1] 4
    [1] 3
    [1] 4
    Accessing Vector Elements

    Access elements using the subscript operator []. R uses 1-based indexing.

    # R program to access vector elements
    
    # Creating a vector
    vec <- c(8, 15, 23, 42, 57)
    
    # Accessing an element by index
    cat('Single element:', vec[3], '\n')
    
    # Accessing multiple elements using c()
    cat('Multiple elements:', vec[c(1, 5)], '\n')

    Output:

    Single element: 23
    Multiple elements: 8 57
    Modifying a Vector

    Example :

    # R program to modify a vector
    
    # Creating a vector
    vec <- c(5, 10, 15, 20)
    
    # Modify specific elements
    vec[2] <- 12
    vec[4] <- 25
    cat('Modified vector:', vec, '\n')
    
    # Modify using a range
    vec[1:3] <- c(7, 14, 21)
    cat('Modified using range:', vec, '\n')

    Output:

    Modified vector: 5 12 15 25
    Modified using range: 7 14 21 25
    Deleting a Vector

    Assign NULL to a vector to delete it.

    # R program to delete a vector
    
    # Creating a vector
    vec <- c(4, 8, 12, 16)
    
    # Deleting the vector
    vec <- NULL
    cat('Deleted vector:', vec)

    Output:

    Deleted vector: NULL
    Sorting a Vector
    # R program to sort a vector
    
    # Creating a vector
    vec <- c(9, 3, 7, 1, 5)
    
    # Sort in ascending order
    asc <- sort(vec)
    cat('Ascending order:', asc, '\n')
    
    # Sort in descending order
    desc <- sort(vec, decreasing = TRUE)
    cat('Descending order:', desc)

    Output:

    Ascending order: 1 3 5 7 9
    Descending order: 9 7 5 3 1

    R – List

    list in R is a generic object consisting of an ordered collection of objects. It is a one-dimensional, heterogeneous data structure, which means it can store different types of data, such as vectors, matrices, characters, and even functions.

    A list is essentially a vector but allows for elements of varying data types. You can create a list using the list() function, and its indexing starts from 1 instead of 0.

    Creating a List

    To create a list in R, you use the list() function. For example, let’s create a list to store details about books, such as their IDs, titles, and total count.

    Example:

    # R program to create a List
    
    # Numeric vector for book IDs
    bookId <- c(101, 102, 103, 104)
    
    # Character vector for book titles
    bookTitle <- c("R Programming", "Data Science", "Machine Learning", "AI")
    
    # Total number of books
    totalBooks <- 4
    
    # Combine all attributes into a list
    bookList <- list(bookId, bookTitle, totalBooks)
    
    print(bookList)

    Output:

    [[1]]
    [1] 101 102 103 104
    
    [[2]]
    [1] "R Programming"    "Data Science"      "Machine Learning" "AI"
    
    [[3]]
    [1] 4
    Naming List Components

    Assigning names to list components makes it easier to access them.

    Example:

    # Named list for a person’s details
    personDetails <- list(name = "Aarav", age = 30, city = "Mumbai")
    
    # Printing the named list
    print(personDetails)

    Output:

    $name
    [1] "Aarav"
    
    $age
    [1] 30
    
    $city
    [1] "Mumbai"
    Accessing R List Components

    1. Access Components by Names: Using the $ operator, you can directly access components by their names.

    Example:

    # List with named components
    bookList <- list(
      "ID" = c(101, 102, 103, 104),
      "Titles" = c("R Programming", "Data Science", "Machine Learning", "AI"),
      "Total Books" = 4
    )
    
    # Access Titles
    cat("Accessing titles using $ operator:\n")
    print(bookList$Titles)

    Output:

    Accessing titles using $ operator:
    [1] "R Programming"    "Data Science"      "Machine Learning" "AI"

    2. Access Components by Indices: You can also access components using indices. Use double brackets [[ ]] for top-level components and single brackets [ ] for inner components.

    Example:

    # Accessing by indices
    cat("Accessing titles using indices:\n")
    print(bookList[[2]])
    
    cat("Accessing a specific title using indices:\n")
    print(bookList[[2]][3])
    
    cat("Accessing the last book ID using indices:\n")
    print(bookList[[1]][4])

    Output:

    Accessing titles using indices:
    [1] "R Programming"    "Data Science"      "Machine Learning" "AI"
    
    Accessing a specific title using indices:
    [1] "Machine Learning"
    
    Accessing the last book ID using indices:
    [1] 104
    Modifying Components of a List

    You can modify the components of a list by accessing them and replacing their values.

    Example:

    # Modify components of a list
    cat("Before modifying the list:\n")
    print(bookList)
    
    # Modify total books count
    bookList$`Total Books` <- 5
    
    # Add a new book ID and title
    bookList[[1]][5] <- 105
    bookList[[2]][5] <- "Deep Learning"
    
    cat("After modifying the list:\n")
    print(bookList)

    Output:

    Before modifying the list:
    $ID
    [1] 101 102 103 104
    
    $Titles
    [1] "R Programming"    "Data Science"      "Machine Learning" "AI"
    
    $`Total Books`
    [1] 4
    
    After modifying the list:
    $ID
    [1] 101 102 103 104 105
    
    $Titles
    [1] "R Programming"    "Data Science"      "Machine Learning" "AI"               "Deep Learning"
    
    $`Total Books`
    [1] 5
    Concatenation of Lists

    You can concatenate two lists using the c() function.

    Example:

    # Original list
    bookList <- list(
      "ID" = c(101, 102, 103, 104),
      "Titles" = c("R Programming", "Data Science", "Machine Learning", "AI")
    )
    
    # New list with book prices
    bookPrices <- list("Prices" = c(500, 600, 700, 800))
    
    # Concatenate lists
    mergedList <- c(bookList, bookPrices)
    
    cat("After concatenating the lists:\n")
    print(mergedList)

    Output:

    $ID
    [1] 101 102 103 104
    
    $Titles
    [1] "R Programming"    "Data Science"      "Machine Learning" "AI"
    
    $Prices
    [1] 500 600 700 800
    Adding Items to a List

    You can append items to a list using the append() function.

    Example:

    # Original list
    myNumbers <- c(10, 20, 30)
    
    # Append a new number
    myNumbers <- append(myNumbers, 40)
    
    # Print updated list
    print(myNumbers)

    Output:

    [1] 10 20 30 40
    Deleting Components of a List

    To delete components, access them and use a negative index.

    Example:

    # List with named components
    bookList <- list(
      "ID" = c(101, 102, 103, 104),
      "Titles" = c("R Programming", "Data Science", "Machine Learning", "AI"),
      "Total Books" = 4
    )
    
    cat("Before deletion:\n")
    print(bookList)
    
    # Delete the "Total Books" component
    bookList <- bookList[-3]
    
    cat("After deleting 'Total Books':\n")
    print(bookList)

    Output:

    Before deletion:
    $ID
    [1] 101 102 103 104
    
    $Titles
    [1] "R Programming"    "Data Science"      "Machine Learning" "AI"
    
    $`Total Books`
    [1] 4
    
    After deleting 'Total Books':
    $ID
    [1] 101 102 103 104
    
    $Titles
    [1] "R Programming"    "Data Science"      "Machine Learning" "AI"

    R – Array

    Arrays are fundamental data storage structures defined with a specific number of dimensions. They are used to allocate space in contiguous memory locations.

    In R Programming, one-dimensional arrays are called vectors, where their single dimension is their length. Two-dimensional arrays are referred to as matrices, which consist of a defined number of rows and columns. Arrays in R hold elements of the same data type. Vectors serve as inputs to create arrays, specifying their dimensions.

    Creating an Array

    In R, arrays can be created using the array() function. The function takes a list of elements and dimensions as inputs to create the desired array.

    Syntax:

    array(data, dim = c(nrow, ncol, nmat), dimnames = names)

    Components:

    • nrow: Number of rows.
    • ncol: Number of columns.
    • nmat: Number of matrices with dimensions nrow * ncol.
    • dimnames: Defaults to NULL. Alternatively, a list can be provided containing names for each component of the array dimensions.
    Uni-Dimensional Array

    A vector, a one-dimensional array, has its length as its dimension. It can be created using the c() function.

    Example:

    vec <- c(10, 20, 30, 40, 50)
    print(vec)
    
    # Displaying the length of the vector
    cat("Length of the vector: ", length(vec))

    Output:

    [1] 10 20 30 40 50
    Length of the vector:  5
    Multi-Dimensional Array

    A matrix, or a two-dimensional array, is defined by rows and columns of the same data type. Matrices are created using the array() function.

    Example:

    # Create a matrix with values from 15 to 26
    mat <- array(15:26, dim = c(2, 3, 2))
    print(mat)

    Output:

    , , 1
         [,1] [,2] [,3]
    [1,]   15   17   19
    [2,]   16   18   20
    
    , , 2
         [,1] [,2] [,3]
    [1,]   21   23   25
    [2,]   22   24   26
    Naming Array Dimensions

    You can assign names to rows, columns, and matrices using vectors for better readability.

    Example:

    rows <- c("Row1", "Row2")
    columns <- c("Col1", "Col2", "Col3")
    matrices <- c("Matrix1", "Matrix2")
    
    named_array <- array(1:12, dim = c(2, 3, 2),
                         dimnames = list(rows, columns, matrices))
    print(named_array)

    Output:

    , , Matrix1
         Col1 Col2 Col3
    Row1    1    3    5
    Row2    2    4    6
    
    , , Matrix2
         Col1 Col2 Col3
    Row1    7    9   11
    Row2    8   10   12
    Accessing Arrays

    You can access elements of arrays using indices for each dimension. Names or positions can be used.

    Example:

    vec <- c(5, 10, 15, 20, 25)
    cat("Vector:", vec)
    cat("Second element:", vec[2])

    Output:

    Vector: 5 10 15 20 25
    Second element: 10
    Accessing Matrices in an Array

    Example:

    rows <- c("A", "B")
    columns <- c("X", "Y", "Z")
    matrices <- c("M1", "M2")
    
    multi_array <- array(1:12, dim = c(2, 3, 2),
                         dimnames = list(rows, columns, matrices))
    
    # Accessing first matrix
    print("Matrix M1")
    print(multi_array[, , "M1"])
    
    # Accessing second matrix by index
    print("Matrix 2")
    print(multi_array[, , 2])

    Output:

    Matrix M1
         X Y Z
    A    1 3 5
    B    2 4 6
    
    Matrix 2
         X Y Z
    A    7 9 11
    B    8 10 12
    Accessing Specific Rows and Columns

    Example:

    print("First row of Matrix 1")
    print(multi_array[1, , "M1"])
    
    print("Second column of Matrix 2")
    print(multi_array[, 2, 2])

    Output:

    First row of Matrix 1
    X Y Z
    1 3 5
    
    Second column of Matrix 2
    A 9
    B 10
    Modifying Arrays

    Adding Elements to Arrays: New elements can be added at specific positions or appended to the array.

    Example:

    vec <- c(1, 2, 3, 4)
    
    # Adding an element using c()
    vec <- c(vec, 5)
    print("After appending an element:")
    print(vec)
    
    # Using append() to add after the 2nd element
    vec <- append(vec, 10, after = 2)
    print("After using append:")
    print(vec)

    Output:

    After appending an element:
    [1] 1 2 3 4 5
    
    After using append:
    [1]  1  2 10  3  4  5

    Removing Elements

    Elements can be removed using logical conditions or indices.

    Example:

    vec <- c(1, 2, 3, 4, 5, 6)
    vec <- vec[vec != 4]  # Removing element with value 4
    print(vec)

    Output:

    [1] 1 2 3 5 6

    R – Matrices

    Matrices are two-dimensional, homogeneous data structures arranged in rows and columns.

    Creating a Matrix

    To create a matrix, use the matrix() function:

    matrix(data, nrow, ncol, byrow, dimnames)
    Parameters:
    • data: Elements to include.
    • nrow: Number of rows.
    • ncol: Number of columns.
    • byrow: Logical (TRUE for row-wise, FALSE for column-wise order).
    • dimnames: Names of rows and columns.

    Example:

    A <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3, byrow = TRUE)
    rownames(A) <- c("a", "b", "c")
    colnames(A) <- c("c", "d", "e")
    print(A)

    Output:

    c d e
    a 1 2 3
    b 4 5 6
    c 7 8 9
    Special Matrices

    1. Constant Matrix:

    matrix(5, 3, 3)

    2. Diagonal Matrix:

    diag(c(5, 3, 3), 3, 3)

    3. Identity Matrix:

    diag(1, 3, 3)
    Accessing Matrix Elements

    Use [row, col] notation:

    • Access rows: matrix[1:2, ]
    • Access columns: matrix[, 1:2]
    • Access specific element: matrix[1, 2]
    • Access submatrices: matrix[1:3, 1:2]
    Modifying Matrix Elements

    Direct assignment:

    Example:

    # Create a matrix
    matrix <- matrix(1:9, nrow = 3, ncol = 3)
    
    # Modify the element in the 3rd row and 3rd column
    matrix[3, 3] <- 30
    
    # Print the modified matrix
    print(matrix)

    Output:

    [,1] [,2] [,3]
    [1,]    1    4    7
    [2,]    2    5    8
    [3,]    3    6   30
    Matrix Concatenation

    Add a Row: You can add a row to the matrix using the rbind() function.

    Example:

    # Create a new row
    new_row <- c(10, 11, 12)
    
    # Add the new row to the matrix
    matrix <- rbind(matrix, new_row)
    
    # Print the updated matrix
    print(matrix)

    Output:

    [,1] [,2] [,3]
    [1,]    1    4    7
    [2,]    2    5    8
    [3,]    3    6   30
    [4,]   10   11   12

    Add a Column: You can add a column to the matrix using the cbind() function.

    # Create a new column
    new_col <- c(13, 14, 15, 16)
    
    # Add the new column to the matrix
    matrix <- cbind(matrix, new_col)
    
    # Print the updated matrix
    print(matrix)

    Output:

    [,1] [,2] [,3] [,4]
    [1,]    1    4    7   13
    [2,]    2    5    8   14
    [3,]    3    6   30   15
    [4,]   10   11   12   16
    Accessing Submatrices in R:

    You can access specific parts of a matrix (submatrices) using the colon : operator in R.

    Example:

    # R program to demonstrate accessing submatrices
    
    # Create a 4x4 matrix
    M = matrix(
      c(10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160),
      nrow = 4,
      ncol = 4,
      byrow = TRUE
    )
    cat("The 4x4 matrix:\n")
    print(M)
    
    cat("\nAccessing the first two rows and the first three columns:\n")
    print(M[1:2, 1:3])

    Output:

    The 4x4 matrix:
         [,1] [,2] [,3] [,4]
    [1,]   10   20   30   40
    [2,]   50   60   70   80
    [3,]   90  100  110  120
    [4,]  130  140  150  160
    
    Accessing the first two rows and the first three columns:
         [,1] [,2] [,3]
    [1,]   10   20   30
    [2,]   50   60   70
    Modifying Elements of an R-Matrix:

    You can modify elements in a matrix by directly assigning new values.

    Example:

    # R program to demonstrate modifying elements in a matrix
    
    # Create a 3x3 matrix
    M = matrix(
      c(2, 4, 6, 8, 10, 12, 14, 16, 18),
      nrow = 3,
      ncol = 3,
      byrow = TRUE
    )
    cat("Original matrix:\n")
    print(M)
    
    # Change the element in the 2nd row and 2nd column
    M[2, 2] = 100
    
    cat("\nMatrix after modification:\n")
    print(M)

    Output:

    Original matrix:
         [,1] [,2] [,3]
    [1,]    2    4    6
    [2,]    8   10   12
    [3,]   14   16   18
    
    Matrix after modification:
         [,1] [,2] [,3]
    [1,]    2    4    6
    [2,]    8  100   12
    [3,]   14   16   18
    Matrix Concatenation in R:

    Concatenation merges rows or columns of a matrix.

    Adding Rows Using rbind():

    # R program to demonstrate adding a row
    
    # Create a 2x3 matrix
    M = matrix(
      c(1, 2, 3, 4, 5, 6),
      nrow = 2,
      ncol = 3,
      byrow = TRUE
    )
    cat("Original matrix:\n")
    print(M)
    
    # Define a new row
    new_row = c(7, 8, 9)
    
    # Add the new row
    M_updated = rbind(M, new_row)
    
    cat("\nMatrix after adding a new row:\n")
    print(M_updated)

    Output:

    Original matrix:
         [,1] [,2] [,3]
    [1,]    1    2    3
    [2,]    4    5    6
    
    Matrix after adding a new row:
         [,1] [,2] [,3]
    [1,]    1    2    3
    [2,]    4    5    6
    [3,]    7    8    9

    Adding Columns Using cbind():

    Adding Columns Using cbind():
    R
    Copy
    Edit

    Output:

    Original matrix:
         [,1] [,2]
    [1,]   10   20
    [2,]   30   40
    
    Matrix after adding a new column:
         [,1] [,2] [,3]
    [1,]   10   20   50
    [2,]   30   40   60
    Deleting Rows and Columns:

    You can delete rows or columns by using negative indices.

    Deleting a Row:

    # R program to demonstrate row deletion
    
    # Create a 3x3 matrix
    M = matrix(
      c(5, 10, 15, 20, 25, 30, 35, 40, 45),
      nrow = 3,
      ncol = 3,
      byrow = TRUE
    )
    cat("Matrix before row deletion:\n")
    print(M)
    
    # Delete the 2nd row
    M_updated = M[-2, ]
    
    cat("\nMatrix after deleting the 2nd row:\n")
    print(M_updated)

    Output:

    Matrix before row deletion:
         [,1] [,2] [,3]
    [1,]    5   10   15
    [2,]   20   25   30
    [3,]   35   40   45
    
    Matrix after deleting the 2nd row:
         [,1] [,2] [,3]
    [1,]    5   10   15
    [2,]   35   40   45

    Deleting a Column:

    # R program to demonstrate column deletion
    
    # Create a 3x3 matrix
    M = matrix(
      c(2, 4, 6, 8, 10, 12, 14, 16, 18),
      nrow = 3,
      ncol = 3,
      byrow = TRUE
    )
    cat("Matrix before column deletion:\n")
    print(M)
    
    # Delete the 3rd column
    M_updated = M[, -3]
    
    cat("\nMatrix after deleting the 3rd column:\n")
    print(M_updated)

    Output:

    Matrix before column deletion:
         [,1] [,2] [,3]
    [1,]    2    4    6
    [2,]    8   10   12
    [3,]   14   16   18
    
    Matrix after deleting the 3rd column:
         [,1] [,2]
    [1,]    2    4
    [2,]    8   10
    [3,]   14   16
  • Input and Output

    Taking Input from User in R Programming

    Developers often need to interact with users to gather data or provide results. Most modern programs use dialog boxes or console input for this purpose. In R, it is also possible to take input from the user through two main methods:

    1. Using the readline() method
    2. Using the scan() method
    Using readline() Method

    The readline() method in R accepts input in string format. If a user inputs a number, such as 123, it is initially treated as a string ("123"). To use the input in other data types like integers, numeric, or dates, R provides functions to convert the input to the desired type.

    Conversion Functions in R:

    • as.integer(n) – Converts to integer
    • as.numeric(n) – Converts to numeric types (float, double, etc.)
    • as.complex(n) – Converts to complex numbers (e.g., 3+2i)
    • as.Date(n) – Converts to a date

    Syntax:

    var = readline();
    var = as.integer(var);
    # You can also use `<-` instead of `=`

    Example:

    # R program to demonstrate input using readline()
    
    # Taking input using readline()
    var = readline();
    
    # Convert the input to an integer
    var = as.integer(var);
    
    # Print the value
    print(var)

    Output:

    123
    [1] 123

    You can also display a message in the console to guide the user about what to input. Use the prompt argument inside the readline() function for this. The prompt argument is helpful for user interaction but is not mandatory.

    Syntax:

    var1 = readline(prompt = "Enter any number: ");
    or,
    var1 = readline("Enter any number: ");

    Example:

    # R program to demonstrate input with a prompt message
    
    # Taking input with a message
    var = readline(prompt = "Enter any number: ");
    
    # Convert the input to an integer
    var = as.integer(var);
    
    # Print the value
    print(var)

    Output:

    Enter any number: 123
    [1] 123
    Nomenclature Rules for R Variables
    1. Variable names can include alphabets, numbers, dot (.), and underscore (_).
      Example: var_1 is valid.
    2. No special characters (except dot and underscore) are allowed.
      Example: var$1 or var#1 is invalid.
    3. Variable names must start with alphabets or a dot (.).
      Example: my_var or .myVar is valid.
    4. Variable names must not begin with numbers or underscores.
      Example: 1var or _var is invalid.
    5. If a variable starts with a dot, the character immediately following cannot be a number.
      Example: .3var is invalid.
    6. Reserved keywords in R (e.g., TRUEFALSE) cannot be used as variable names.
    Important Functions for R Variables

    1. class() Function: This function identifies the data type of a variable.

    Syntax:

    class(variable)

    Example:

    number = 42
    print(class(number))

    Output:

    [1] "numeric"

    2. ls() Function: Lists all the variables in the current R workspace.

    Syntax:

    ls()

    Example:

    # Assigning values to variables
    name = "Alice"
    age <- 30
    height -> 5.5
    
    print(ls())

    Output:

    [1] "age" "height" "name"

    3. rm() Function: Deletes a specified variable from the workspace.

    Syntax:

    rm(variable)

    Example:

    # Assigning and removing a variable
    country = "India"
    rm(country)
    print(country)

    Output:

    Error in print(country): object 'country' not found
    Scope of Variables in R

    1. Global Variables: Accessible throughout the program and declared outside of any block or function.

    Example:

    # Declaring and accessing global variables
    global_var = 10
    
    display = function() {
      print(global_var)
    }
    
    display()
    
    # Modifying the global variable
    global_var = 20
    display()

    Output:

    [1] 10
    [1] 20

    2. Local Variables: Accessible only within the block or function where they are declared.

    Example:

    # Declaring and using a local variable
    my_function = function() {
      local_var = "This is local"
      print(local_var)
    }
    
    cat("Inside the function:\n")
    my_function()
    
    cat("Outside the function:\n")
    print(local_var)

    Output:

    Inside the function:
    [1] "This is local"
    Outside the function:
    Error in print(local_var): object 'local_var' not found
    Difference Between Local and Global Variables in R
    AspectGlobal VariablesLocal Variables
    ScopeAccessible throughout the program.Accessible only within the function/block.
    LifetimeExist until the program finishes execution or is removed explicitly.Exist only during the function/block execution.
    Naming ConflictsProne to conflicts as accessible globally.Limited scope minimizes conflicts.
    Memory UsageOccupies memory throughout the program’s execution.Utilized temporarily, thus conserving memory.

    Scope of Variable in R

    Variables in R are containers used to store data values. They serve as references, or pointers, to objects in memory. When a variable is assigned a value, it points to the memory location where the value is stored. Variables in R can hold vectors, collections of vectors, or combinations of various R objects.

    Example:

    # Assigning a value using the equal sign
    num_values = c(4, 5, 6, 7)
    print(num_values)
    
    # Assigning values using the leftward arrow
    languages <- c("JavaScript", "R")
    print(languages)
    
    # Assigning a vector
    numbers = c(10, 20, 30)
    print(numbers)
    
    names = c("Alice", "Bob", "Carol")
    print(names)
    
    # Creating a list of vectors
    combined_list = list(numbers, names)
    print(combined_list)

    Output:

    [1] 4 5 6 7
    [1] "JavaScript" "R"
    [1] 10 20 30
    [1] "Alice" "Bob" "Carol"
    [[1]]
    [1] 10 20 30
    
    [[2]]
    [1] "Alice" "Bob" "Carol"
    Naming Conventions for Variables

    Variable names in R must follow these rules:

    • They must start with an alphabet.
    • Only alphanumeric characters, underscores (_), and periods (.) are allowed.
    • Special characters such as !@#$ are not allowed.

    Example:

    # Valid variable names
    value1 = 15
    student_name = "John"
    course.Name = "Data Science"
    
    # Invalid variable names
    # 1value = 20
    # student@name = "John"

    Error:

    Error: unexpected symbol in "1value"
    Error: unexpected symbol in "student@name"
    Scope of Variables

    Global Variables: Global variables are accessible throughout the program. They are usually declared outside all functions and remain in memory until the program ends.

    Example:

    # Defining a global variable
    global_value = 42
    
    # Function accessing the global variable
    show_value = function() {
      print(global_value)
    }
    
    show_value()
    
    # Updating the global variable
    global_value = 100
    show_value()

    Output:

    [1] 42
    [1] 100

    Local Variables: Local variables exist only within the scope of the function or block in which they are defined. They are not accessible outside that block.

    Example:

    my_function = function() {
      # Defining a local variable
      local_value = 25
    }
    
    # Attempting to access the local variable
    print(local_value)

    Error:

    Error in print(local_value) : object 'local_value' not found

    To access the value, use print() within the function:

    my_function = function() {
      local_value = 25
      print(local_value)
    }
    
    my_function()

    Output:

    [1] 25

    Accessing Global Variables: Global variables are accessible across the program, but local variables are restricted to their scope.

    Example:

    set_value = function() {
      # Local variable
      local_var <- 15
    }
    
    set_value()
    print(local_var)

    Error:

    Error in print(local_var) : object 'local_var' not found

    To create or modify global variables inside a function, use the super assignment operator (<<-):

    set_global = function() {
      # Making a global variable
      global_var <<- 50
      print(global_var)
    }
    
    set_global()
    print(global_var)

    Output:

    [1] 50
    [1] 50

    Dynamic Scoping in R Programming

    R is an open-source programming language extensively used for statistical analysis and data visualization. It operates through a command-line interface and is compatible with popular platforms like Windows, Linux, and macOS. As a cutting-edge programming tool, R employs lexical scoping or static scoping as its primary mechanism for resolving free variables, distinguishing it from other languages that may use dynamic scoping.

    Dynamic Scoping: The Concept

    Consider the following function:

    h <- function(a, b) {
      a^2 + b/c
    }

    Here, the function h has two formal arguments a and b. Inside the function body, there is another symbol c, which is a free variable. Scoping rules determine how free variables like c are resolved. Free variables are neither formal arguments nor local variables assigned within the function.

    Lexical Scoping in R
    Under lexical scoping, the value of a free variable is resolved in the environment where the function was defined. If the variable’s value isn’t found in the defining environment, the search continues in its parent environment until the global environment or namespace is reached. If the variable remains undefined even in the global environment, an error is raised.

    Illustrative Example of Lexical Scoping
    create.power <- function(m) {
      power.calc <- function(num) {
        num ^ m
      }
      power.calc
    }
    
    cube <- create.power(3)
    square <- create.power(2)
    
    print(cube(4))   # Output: [1] 64
    print(square(5)) # Output: [1] 25

    Here, the function create.power generates a closure, where m is a free variable inside the nested power.calc function. The value of m is determined from the environment where create.power was defined.

    Inspecting Function Environments
    ls(environment(cube))
    # Output: [1] "m" "power.calc"
    
    get("m", environment(cube))
    # Output: [1] 3
    
    ls(environment(square))
    # Output: [1] "m" "power.calc"
    
    get("m", environment(square))
    # Output: [1] 2

    The environment() function retrieves the environment of a function, while ls() lists the variables in that environment. The get() function fetches the value of a specific variable within the environment.

    Comparing Lexical and Dynamic Scoping

    Let’s take another example to illustrate the difference:

    z <- 5
    
    f <- function(x) {
      z <- 3
      y <- function(p) {
        p + z
      }
      y(x)
    }
    
    y <- function(p) {
      p * z
    }

    Lexical Scoping: In this scenario, z in y(x) will resolve to 3, as it is found in the local environment of f.
    Dynamic Scoping: If dynamic scoping were used, z would resolve to 5, as it would be looked up in the calling environment.

    Output with Lexical Scoping:

    print(f(2))  # Output: [1] 5

    Example Demonstrating Errors with Free Variables

    y <- 4
    
    g <- function(x) {
      b <- 2
      x + b + y
    }
    
    print(g(3))  # Output: [1] 9

    If y is not defined in the environment, calling g(3) results in the following error:

    Error in g(3): object 'y' not found

    To fix this, ensure y has a value assigned before calling the function.

    Lexical Scoping in R Programming

    Lexical Scoping in R programming means that the values of the free variables are searched for in the environment in which the function was defined. An environment is a collection of symbols, value, and pair, every environment has a parent environment it is possible for an environment to have multiple children but the only environment without the parent is the empty environment. If the value of the symbol is not found in the environment in which the function was defined then the search is continued in the parent environment. In R, the free variable bindings are resolve by first looking in the environment in which the function was created. This is called Lexical Scoping.

    Why Lexical Scoping?

    Lexical scoping determines how R identifies the value of a variable based on the function’s definition rather than its execution context. This built-in behavior simplifies understanding variable resolution in R. Lexical scoping allows users to focus solely on the function’s definition, rather than its invocation, to predict how variables are resolved. This concept is especially beneficial in statistical computations.

    The term “lexical” in lexical scoping originates from the concept of “lexing” in computer science, which is the process of breaking down code into meaningful units that can be interpreted by a programming language.

    Example:

    f <- function(a, b) {
      a + b + c
    }
    
    c <- 5
    f(2, 3)

    Output:

    [1] 10

    In this case:

    • a and b are formal arguments.
    • c is a free variable. Its value is retrieved from the environment where the function was defined.
    Principles of Lexical Scoping

    There are four fundamental principles of lexical scoping in R:

    1. Name Masking
    2. Functions vs Variables
    3. A Fresh Start
    4. Dynamic Lookup

    1. Name Masking: When a variable’s name is not defined within a function, R looks for the variable in the parent environment.

    Example:

    x <- 15
    y <- function(a, b) {
      a + b + x
    }
    
    y(5, 10)

    Output:

    [1] 30

    Explanation: The function adds 5, 10, and the value of x from the global environment.

    If a variable is defined inside the function, it masks the variable from the parent environment.

    Example:

    x <- 20
    y <- function() {
      x <- 5
      x + 10
    }
    
    y()

    Output:

    [1] 15

    Explanation: The local definition of x within the function takes precedence.

    2. Functions vs Variables: R applies the same scoping rules to functions and variables.

    Example:

    f <- function(x) x * 2
    g <- function() {
      f <- function(x) x + 5
      f(3)
    }
    
    g()

    Output:

    [1] 8

    3. A Fresh Start: Every time a function is called, R creates a new environment, ensuring that the function’s execution is independent of previous calls.

    Example:

    a <- function() {
      if (!exists("y")) {
        y <- 10
      } else {
        y <- y + 10
      }
      y
    }
    
    a()

    Output:

    [1] 10

    4. Dynamic Lookup: Lexical scoping resolves where to look for variable values, but the lookup occurs at the time of function execution.

    Example:

    h <- function() z + 5
    z <- 10
    h()

    Output:

    [1] 15
    Identifying Global Variables

    The findGlobals() function from the codetools package identifies global variables used within a function. This can help in understanding external dependencies.

    Example:

    xGlobal <- runif(5)
    yGlobal <- runif(5)
    
    f <- function() {
      x <- xGlobal
      y <- yGlobal
      plot(y ~ x)
    }
    
    codetools::findGlobals(f)

    Output:

    [1] "{"       "~"       "<-"      "xGlobal" "yGlobal" "plot"