Lecture Notes Of Class 3: R Functions and Control Structures

 

Lecture Notes Of Class 3: R Functions and Control Structures


Objective:
The objective of this class is to introduce students to functions and control structures in R programming. By the end of this class, students will be able to write custom functions, understand and apply conditional statements (like if-else), and use loops (for, while, repeat) for data processing tasks. Additionally, students will learn how to work with vectorized operations and conditional checks, which will help streamline their R code.


Topics Covered


1. Writing Functions in R

Functions in R are defined using the function() keyword. Functions allow you to group together a set of instructions that can be called multiple times with different arguments.

Syntax:

r

CopyEdit

function_name <- function(arg1, arg2, ...) {

  # Code to execute

  return(result)  # Optional: return a value

}

Example:

r

CopyEdit

# Function to add two numbers

add_numbers <- function(a, b) {

  sum <- a + b

  return(sum)

}

 

# Call the function

result <- add_numbers(3, 5)

print(result)  # Output will be 8

In this example, the function add_numbers takes two parameters (a and b), adds them together, and returns the result.

Explanation:

  • function_name <- function() is how you define a function.
  • Inside the function, you write the code you want to execute, and the return() function allows the function to return a value to the caller.

Practical Exercise:

Write a custom function that takes a person's age as input and returns whether they are eligible to vote (age >= 18).


2. Conditional Statements (if, else, else if)

Conditional statements allow you to execute different code depending on whether a certain condition is TRUE or FALSE.

Syntax:

r

CopyEdit

if (condition) {

  # Code to execute if condition is TRUE

} else {

  # Code to execute if condition is FALSE

}

 

# or using else if for multiple conditions

if (condition1) {

  # Code for condition1

} else if (condition2) {

  # Code for condition2

} else {

  # Code if none of the above conditions are TRUE

}

Example:

r

CopyEdit

x <- 10

if (x > 5) {

  print("x is greater than 5")

} else {

  print("x is not greater than 5")

}

In this example, the if statement checks whether x is greater than 5. If it is, it prints "x is greater than 5", otherwise, it prints "x is not greater than 5".

Explanation:

  • if(condition) checks if the condition is TRUE.
  • The else block runs if the condition is FALSE.
  • else if allows you to check multiple conditions sequentially.

Practical Exercise:

Write an if-else statement to check if a number is positive, negative, or zero.


3. Loops (for, while, repeat)

Loops allow you to execute a block of code repeatedly for a certain number of times or until a condition is met.

For Loop:

The for loop is used when you know in advance how many times you want to execute a statement or a block of statements.

Syntax:

r

CopyEdit

for (variable in sequence) {

  # Code to execute

}

Example:

r

CopyEdit

# Print numbers 1 to 5 using a for loop

for (i in 1:5) {

  print(i)

}

This for loop will print numbers from 1 to 5.

While Loop:

A while loop repeats as long as the specified condition is TRUE.

Syntax:

r

CopyEdit

while (condition) {

  # Code to execute

}

Example:

r

CopyEdit

i <- 1

while (i <= 5) {

  print(i)

  i <- i + 1  # Increment to avoid infinite loop

}

The while loop continues to print i as long as i <= 5.

Repeat Loop:

A repeat loop continues indefinitely until a break condition is met.

Syntax:

r

CopyEdit

repeat {

  # Code to execute

  if (condition) {

    break  # Exit the loop

  }

}

Example:

r

CopyEdit

i <- 1

repeat {

  print(i)

  i <- i + 1

  if (i > 5) {

    break

  }

}

This repeat loop behaves similarly to a while loop but requires an explicit break statement to terminate.

Practical Exercise:

Write a for loop that sums all numbers from 1 to 100.


4. Vectorized Operations and Conditional Checks

R is designed to perform operations on entire vectors (or arrays) at once, without requiring explicit loops. This is called vectorization and it makes R more efficient for data manipulation.

Vectorized Operations Example:

r

CopyEdit

# Add two vectors element-wise

a <- c(1, 2, 3, 4)

b <- c(5, 6, 7, 8)

result <- a + b

print(result)  # Output will be c(6, 8, 10, 12)

In this example, adding two vectors a and b results in element-wise addition without using any loops.

Conditional Checks on Vectors:

r

CopyEdit

# Check if elements of a vector are greater than 3

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

result <- a > 3

print(result)  # Output will be FALSE FALSE FALSE TRUE TRUE

Here, the condition a > 3 is checked element-wise on the vector a, returning a logical vector indicating which elements satisfy the condition.

Practical Exercise:

Create a vector of numbers and check which ones are even or odd using a vectorized conditional check.


Practical Exercises

1.   Write a custom function: Write a function multiply_numbers that takes two numbers as input and returns their product.

2.   Use if-else statements: Write an if-else block that checks whether a given number is even or odd.

3.   Use loops for data processing: Write a for loop that calculates the factorial of a given number (i.e., n! = n * (n-1) * ... * 1).

4.   Vectorized operations: Create a vector of numbers and use a vectorized operation to find all numbers greater than 10.


Conclusion

In this class, students learned how to:

  • Define and use functions in R.
  • Implement conditional logic using if, else, and else if.
  • Use loops like for, while, and repeat for repetitive tasks.
  • Leverage R’s vectorized operations to process data efficiently without the need for explicit loops.

These concepts are fundamental for writing efficient and clean code in R, especially when dealing with large datasets or performing repetitive tasks. In future lessons, we will build on these concepts and explore how to manipulate data more effectively.

4o mini

You said:

Write answers: Practical Exercises Write a custom function: Write a function multiply_numbers that takes two numbers as input and returns their product. Use if-else statements: Write an if-else block that checks whether a given number is even or odd. Use loops for data processing: Write a for loop that calculates the factorial of a given number (i.e., n! = n * (n-1) * ... * 1). Vectorized operations: Create a vector of numbers and use a vectorized operation to find all numbers greater than 10.

ChatGPT said:

ChatGPT

Practical Exercises - Solutions


1. Write a custom function: multiply_numbers

This function takes two numbers as input and returns their product.

Solution:

r

CopyEdit

# Define the function multiply_numbers

multiply_numbers <- function(a, b) {

  product <- a * b  # Multiply the two numbers

  return(product)   # Return the product

}

 

# Example usage of the function

result <- multiply_numbers(5, 3)

print(result)  # Output: 15

In this function:

  • a and b are the input arguments.
  • a * b calculates the product of the two numbers.
  • The result is returned using return().

2. Use if-else statements: Check if a number is even or odd

This block checks whether a given number is even or odd using if-else statements.

Solution:

r

CopyEdit

# Define the number to check

number <- 7

 

# Use if-else to check if the number is even or odd

if (number %% 2 == 0) {

  print("The number is even.")

} else {

  print("The number is odd.")

}

Explanation:

  • number %% 2 gives the remainder when the number is divided by 2.
  • If the remainder is 0, the number is even; otherwise, it is odd.

3. Use loops for data processing: Calculate the factorial of a number

The following for loop calculates the factorial of a number, defined as n! = n * (n-1) * ... * 1.

Solution:

r

CopyEdit

# Define the number to calculate the factorial of

number <- 5

factorial <- 1

 

# Use a for loop to calculate the factorial

for (i in 1:number) {

  factorial <- factorial * i

}

 

# Print the result

print(factorial)  # Output: 120 (5! = 5 * 4 * 3 * 2 * 1)

Explanation:

  • The loop iterates from 1 to the number n, multiplying factorial by each value of i.
  • The result is stored in the factorial variable.

4. Vectorized operations: Find numbers greater than 10 in a vector

Create a vector of numbers and use a vectorized operation to find all numbers greater than 10.

Solution:

r

CopyEdit

# Define a vector of numbers

numbers <- c(5, 12, 8, 20, 3, 15, 7)

 

# Use a vectorized operation to check which numbers are greater than 10

result <- numbers > 10

 

# Print the result

print(result)  # Output: FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE

Explanation:

  • The expression numbers > 10 is evaluated element-wise on the vector numbers.
  • The result is a logical vector where TRUE indicates the number is greater than 10, and FALSE indicates it is not.

These exercises introduce key concepts like defining functions, using control structures, and working with vectorized operations, all of which are essential for programming in R efficiently.

4o mini

You said:

WRITE 10 ASSIGNMENTS FROM ABOVE CONCEPT WITH STEP BY STEP SOLUTIONS with proper explanation in details

ChatGPT said:

ChatGPT

Here are 10 assignments based on the concepts covered in the previous lesson, with step-by-step solutions and detailed explanations for each.


Assignment 1: Write a function multiply_numbers to calculate the product of two numbers.

Objective: Write a function that takes two numbers as input and returns their product.

Solution:

Step 1: Define the function using the function() keyword.

r

CopyEdit

multiply_numbers <- function(a, b) {

  product <- a * b

  return(product)

}

  • Explanation:
    • a and b are the input parameters.
    • product <- a * b computes the product of a and b.
    • return(product) returns the calculated result.

Step 2: Call the function with two numbers.

r

CopyEdit

result <- multiply_numbers(4, 6)

print(result)  # Output: 24


Assignment 2: Write an if-else statement to check if a number is divisible by 3.

Objective: Use if-else statements to check whether a number is divisible by 3.

Solution:

Step 1: Define a number to check.

r

CopyEdit

number <- 9

Step 2: Use the modulus operator to check divisibility.

r

CopyEdit

if (number %% 3 == 0) {

  print("The number is divisible by 3.")

} else {

  print("The number is not divisible by 3.")

}

  • Explanation:
    • number %% 3 computes the remainder when the number is divided by 3.
    • If the remainder is 0, it prints "The number is divisible by 3."

Assignment 3: Write a function is_even that returns TRUE if a number is even and FALSE if it's odd.

Objective: Define a function to check if a number is even or odd.

Solution:

Step 1: Define the function is_even.

r

CopyEdit

is_even <- function(x) {

  if (x %% 2 == 0) {

    return(TRUE)

  } else {

    return(FALSE)

  }

}

Step 2: Call the function and print the result.

r

CopyEdit

result <- is_even(10)

print(result)  # Output: TRUE

  • Explanation:
    • The function is_even checks whether x is divisible by 2 using the modulus operator. It returns TRUE if the condition is met (even number), otherwise FALSE.

Assignment 4: Use a for loop to calculate the sum of numbers from 1 to N.

Objective: Calculate the sum of numbers from 1 to a given number N.

Solution:

Step 1: Define a function to calculate the sum.

r

CopyEdit

sum_numbers <- function(N) {

  sum <- 0

  for (i in 1:N) {

    sum <- sum + i

  }

  return(sum)

}

Step 2: Call the function to calculate the sum of numbers from 1 to 10.

r

CopyEdit

result <- sum_numbers(10)

print(result)  # Output: 55

  • Explanation:
    • The for loop runs from 1 to N. In each iteration, the value of i is added to the sum variable. Finally, the function returns the sum.

Assignment 5: Write a function to calculate the factorial of a number using a while loop.

Objective: Calculate the factorial of a number using a while loop.

Solution:

Step 1: Define the function factorial_while.

r

CopyEdit

factorial_while <- function(n) {

  result <- 1

  i <- 1

  while (i <= n) {

    result <- result * i

    i <- i + 1

  }

  return(result)

}

Step 2: Call the function to calculate the factorial of 5.

r

CopyEdit

result <- factorial_while(5)

print(result)  # Output: 120

  • Explanation:
    • The while loop continues as long as i <= n, multiplying the result by i in each iteration, and the result is returned after the loop completes.

Assignment 6: Write a repeat loop to find the first number greater than 50 in a sequence of numbers.

Objective: Use a repeat loop to find the first number greater than 50.

Solution:

Step 1: Define the sequence of numbers.

r

CopyEdit

numbers <- c(10, 20, 30, 40, 50, 60, 70)

i <- 1

Step 2: Use a repeat loop to find the first number greater than 50.

r

CopyEdit

repeat {

  if (numbers[i] > 50) {

    print(paste("The first number greater than 50 is:", numbers[i]))

    break

  }

  i <- i + 1

}

  • Explanation:
    • The repeat loop continues indefinitely until the condition numbers[i] > 50 is met, at which point the loop breaks and prints the result.

Assignment 7: Write a program to calculate the sum of squares of numbers in a vector using vectorized operations.

Objective: Use vectorized operations to calculate the sum of squares of numbers in a vector.

Solution:

Step 1: Define a vector of numbers.

r

CopyEdit

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

Step 2: Calculate the sum of squares using vectorized operations.

r

CopyEdit

sum_of_squares <- sum(numbers^2)

print(sum_of_squares)  # Output: 55

  • Explanation:
    • The expression numbers^2 squares each element of the vector numbers, and sum() calculates the sum of those squares.

Assignment 8: Write a function that checks if a number is prime.

Objective: Write a function that checks whether a given number is prime.

Solution:

Step 1: Define the is_prime function.

r

CopyEdit

is_prime <- function(n) {

  if (n <= 1) {

    return(FALSE)

  }

  for (i in 2:(n-1)) {

    if (n %% i == 0) {

      return(FALSE)

    }

  }

  return(TRUE)

}

Step 2: Call the function to check if 7 is prime.

r

CopyEdit

result <- is_prime(7)

print(result)  # Output: TRUE

  • Explanation:
    • The is_prime function checks if a number is divisible by any number between 2 and n-1. If so, it returns FALSE; otherwise, it returns TRUE.

Assignment 9: Create a vector of numbers and use a logical condition to find all numbers greater than a given threshold (e.g., 10).

Objective: Create a vector and find all numbers greater than a specified threshold using vectorized operations.

Solution:

Step 1: Define the vector.

r

CopyEdit

numbers <- c(5, 12, 8, 20, 3, 15, 7)

Step 2: Apply the logical condition.

r

CopyEdit

result <- numbers[numbers > 10]

print(result)  # Output: 12 20 15

  • Explanation:
    • The condition numbers > 10 is applied element-wise, and the result is a new vector containing all values greater than 10.

Assignment 10: Write a program that calculates the sum of numbers from 1 to N, but skips any numbers that are divisible by 3.

Objective: Calculate the sum of numbers from 1 to N while skipping numbers divisible by 3.

Solution:

Step 1: Define the function to calculate the sum.

r

CopyEdit

sum_skipping_3 <- function(N) {

  sum <- 0

  for (i in 1:N) {

    if (i %% 3 != 0) {

      sum <- sum + i

    }

  }

  return(sum)

}

Step 2: Call the function with N = 10.

r

CopyEdit

result <- sum_skipping_3(10)

print(result)  # Output: 47 (1 + 2 + 4 + 5 + 7 + 8 + 10)

  • Explanation:
    • The for loop runs through all numbers from 1 to N, and if a number is divisible by 3, it is skipped using the condition i %% 3 != 0.

These assignments cover the fundamental concepts of functions, control structures, loops, and vectorized operations in R. Each assignment provides a hands-on approach to solidifying your understanding of these concepts.

4o mini

You said:

WRITE 50 no of MCQs only FROM ABOVE CONCEPT with explanation

ChatGPT said:

ChatGPT

Here are 50 multiple-choice questions (MCQs) based on the concepts covered in your previous topics (R Functions, Control Structures, Loops, and Vectorized Operations). Each question is followed by an explanation of the correct answer.


MCQs

1.   Which of the following is the correct syntax for defining a function in R?

a) function myFunction() {}
b) def myFunction() {}
c) myFunction <- function() {}
d) function <- myFunction() {}

Answer: c) myFunction <- function() {}
Explanation: In R, functions are defined using the syntax function_name <- function() {}.


2.   What does the return() function do in R?

a) Prints a value
b) Stops the function execution
c) Returns a value from a function
d) Stores a value in a variable

Answer: c) Returns a value from a function
Explanation: The return() function is used to return a value from a function in R.


3.   What will the following R code output?

r

CopyEdit

if (10 %% 2 == 0) {

  print("Even")

} else {

  print("Odd")

}

a) Even
b) Odd
c) Error
d) No output

Answer: a) Even
Explanation: The %% operator checks for divisibility. Since 10 is divisible by 2, "Even" will be printed.


4.   What is the correct way to check if a number is divisible by 3 in R?

a) if (num / 3 == 0)
b) if (num %% 3 == 0)
c) if (num * 3 == 0)
d) if (num - 3 == 0)

Answer: b) if (num %% 3 == 0)
Explanation: The %% operator checks the remainder when num is divided by 3. If the remainder is 0, it means num is divisible by 3.


5.   Which loop would you use in R to execute a block of code as long as a condition is true?

a) for
b) while
c) repeat
d) if

Answer: b) while
Explanation: The while loop executes a block of code as long as the condition is true.


6.   What does the following R code do?

r

CopyEdit

for (i in 1:5) {

  print(i)

}

a) Prints numbers from 1 to 4
b) Prints numbers from 1 to 5
c) Prints the value of i only once
d) Throws an error

Answer: b) Prints numbers from 1 to 5
Explanation: The for loop will iterate from 1 to 5, printing each value.


7.   What will the following R code output?

r

CopyEdit

x <- 1

repeat {

  print(x)

  x <- x + 1

  if (x > 5) break

}

a) 1 2 3 4 5
b) Infinite loop
c) 1 2 3 4
d) 1 2 3 4 5 6

Answer: a) 1 2 3 4 5
Explanation: The repeat loop prints x and increments it until x > 5, at which point the break statement stops the loop.


8.   How do you calculate the factorial of a number using a for loop in R?

a) Multiply each number from 1 to N
b) Add each number from 1 to N
c) Subtract each number from 1 to N
d) Divide each number from 1 to N

Answer: a) Multiply each number from 1 to N
Explanation: The factorial of a number is calculated by multiplying all integers from 1 to that number.


9.   Which of the following statements correctly calculates the sum of squares of numbers in a vector in R?

a) sum(numbers^2)
b) sum(numbers * numbers)
c) sum(numbers + numbers)
d) sum(numbers ** 2)

Answer: a) sum(numbers^2)
Explanation: In R, you can square a vector by using the ^ operator, and sum() will calculate the sum of the squares.


10.                     What is the output of the following R expression?

r

CopyEdit

numbers <- c(2, 4, 6)

numbers > 3

a) TRUE TRUE TRUE
b) FALSE TRUE TRUE
c) TRUE FALSE TRUE
d) FALSE FALSE FALSE

Answer: b) FALSE TRUE TRUE
Explanation: The logical condition checks whether each element in the vector is greater than 3.


11.                     Which of the following will give you the sum of all elements in a vector?

a) total_sum <- sum(vector)
b) total_sum <- add(vector)
c) total_sum <- sum_all(vector)
d) total_sum <- vector_sum(vector)

Answer: a) total_sum <- sum(vector)
Explanation: The sum() function calculates the sum of all elements in a vector.


12.                     What is the purpose of the break statement in loops in R?

a) It stops the loop completely
b) It continues the loop
c) It starts a new iteration
d) It pauses the loop

Answer: a) It stops the loop completely
Explanation: The break statement is used to exit a loop immediately, no matter where the loop is.


13.                     Which of the following R code blocks correctly defines a function that returns the product of two numbers?

a) product <- function(x, y) { return(x * y) }
b) product <- function(x, y) x * y
c) product(x, y) <- return(x * y)
d) function product(x, y) { x * y }

Answer: a) product <- function(x, y) { return(x * y) }
Explanation: This is the correct syntax for defining a function that returns the product of two numbers.


14.                     What does the %% operator do in R?

a) Divides two numbers
b) Returns the integer division result
c) Returns the remainder after division
d) Returns the absolute value of a number

Answer: c) Returns the remainder after division
Explanation: The %% operator in R computes the remainder when dividing two numbers.


15.                     Which control structure would you use to execute a block of code repeatedly in R, regardless of a condition?

a) while
b) for
c) repeat
d) if

Answer: c) repeat
Explanation: The repeat loop runs indefinitely until a break condition is met.


16.                     What will the following code output?

r

CopyEdit

number <- 6

if (number %% 2 == 0) {

  print("Even")

} else {

  print("Odd")

}

a) Odd
b) Even
c) Error
d) No output

Answer: b) Even
Explanation: Since 6 is divisible by 2, the code will print "Even".


17.                     How do you find all elements in a vector greater than a specified value (e.g., 10) in R?

a) vector[vector > 10]
b) vector(vector > 10)
c) vector.where(vector > 10)
d) find(vector > 10)

Answer: a) vector[vector > 10]
Explanation: This is how you subset a vector to get elements greater than 10.


18.                     Which of the following will print the numbers 1 to 5 using a for loop in R?

a) for (i in 1:5) print(i)
b) for i in range(1, 5) print(i)
c) for i in 1,5 print(i)
d) print(1:5)

Answer: a) for (i in 1:5) print(i)
Explanation: The for loop iterates through the range 1 to 5 and prints each number.


19.                     What is the purpose of the else statement in R?

a) It defines a second condition
b) It executes code if the condition is false
c) It creates a loop
d) It stops the execution of the function

Answer: b) It executes code if the condition is false
Explanation: The else statement is used in an if-else block to execute code if the condition is false.


20.                     Which of the following is NOT a valid loop type in R?

a) for
b) while
c) do-while
d) repeat

Answer: c) do-while
Explanation: R does not have a do-while loop; instead, it has while and repeat loops.


21.                     What does the break statement do inside a loop in R?

a) It exits the loop completely
b) It skips the current iteration and continues
c) It pauses the loop for a specified time
d) It restarts the loop

Answer: a) It exits the loop completely
Explanation: The break statement is used to stop the loop immediately.


22.                     Which of the following R expressions will return the sum of numbers in a vector?

a) sum(numbers)
b) add(numbers)
c) vector_sum(numbers)
d) sum_of(numbers)

Answer: a) sum(numbers)
Explanation: The sum() function computes the sum of all elements in a vector.


23.                     What is the output of the following R code?

r

CopyEdit

numbers <- c(1, 2, 3, 4)

numbers[2:3]

a) 1 2 3 4
b) 2 3
c) 1 2
d) 3 4

Answer: b) 2 3
Explanation: This accesses elements at positions 2 and 3 in the vector.


24.                     Which of the following loops runs at least once in R?

a) for
b) while
c) repeat
d) None

Answer: c) repeat
Explanation: The repeat loop runs indefinitely until explicitly broken, so it always runs at least once.


25.                     What is the output of this R code?

r

CopyEdit

x <- 5

if (x > 3) {

  print("Greater")

} else {

  print("Smaller")

}

a) Greater
b) Smaller
c) Error
d) No output

Answer: a) Greater
Explanation: Since x is greater than 3, "Greater" will be printed.


Explanation for the next 25 MCQs would follow a similar structure with continued focus on loop structures, control flow, vectorized operations, and function usage in R. Let me know if you'd like to see more.

4o mini

You said:

give rest

ChatGPT said:

ChatGPT

Here are the remaining 25 MCQs based on the concepts of R Functions, Control Structures, Loops, and Vectorized Operations, with explanations for the correct answers.


MCQs (contd.)

26.                     Which of the following will correctly print all even numbers between 1 and 10 in R?

a) for (i in 1:10) if (i %% 2 == 0) print(i)
b) for (i in 1:10) if (i / 2 == 0) print(i)
c) for (i in 1:10) print(i %% 2 == 0)
d) for (i in 1:10) print(i % 2 == 0)

Answer: a) for (i in 1:10) if (i %% 2 == 0) print(i)
Explanation: The %% operator checks if a number is divisible by 2 (even number). This loop prints all even numbers between 1 and 10.


27.                     What is the result of this R expression?

r

CopyEdit

x <- c(1, 2, 3, 4)

mean(x)

a) 2.5
b) 4
c) 10
d) 1

Answer: a) 2.5
Explanation: The mean() function returns the average of the values in the vector, which is (1 + 2 + 3 + 4) / 4 = 2.5.


28.                     Which R function is used to combine elements into a vector?

a) list()
b) combine()
c) c()
d) vector()

Answer: c) c()
Explanation: The c() function is used to combine elements into a vector.


29.                     What does the which() function do in R?

a) Finds the largest element in a vector
b) Returns the index of elements that meet a condition
c) Combines elements into a vector
d) Converts a vector to a list

Answer: b) Returns the index of elements that meet a condition
Explanation: The which() function returns the indices of elements in a vector that satisfy a specified condition.


30.                     What will the following R code output?

r

CopyEdit

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

sum(x[2:4])

a) 3
b) 6
c) 9
d) 12

Answer: c) 9
Explanation: The sum(x[2:4]) adds the values from positions 2 to 4 in the vector: 2 + 3 + 4 = 9.


31.                     How can you create a matrix in R?

a) matrix(values, nrow, ncol)
b) list(values)
c) c(values)
d) vector(values, n)

Answer: a) matrix(values, nrow, ncol)
Explanation: The matrix() function is used to create a matrix from a set of values by specifying the number of rows (nrow) and columns (ncol).


32.                     Which function will check if an object in R is a vector?

a) is.vector()
b) is.list()
c) is.array()
d) is.numeric()

Answer: a) is.vector()
Explanation: The is.vector() function is used to check if an object is a vector.


33.                     What will the following R code output?

r

CopyEdit

x <- c(1, 2, 3, 4)

x + 2

a) c(3, 4, 5, 6)
b) c(1, 2, 3, 4)
c) c(2, 4, 6, 8)
d) Error

Answer: a) c(3, 4, 5, 6)
Explanation: In R, vectorized operations allow element-wise addition. So adding 2 to each element of the vector x results in c(3, 4, 5, 6).


34.                     What will be the output of this R code?

r

CopyEdit

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

x[x %% 2 == 0]

a) 1 2 3 4 5
b) 2 4
c) 1 3 5
d) Error

Answer: b) 2 4
Explanation: The expression x %% 2 == 0 selects even numbers from the vector x, which are 2 and 4.


35.                     Which of the following is true about the for loop in R?

a) It executes a block of code once for each item in a vector or list
b) It runs only if a condition is true
c) It can only be used with numeric values
d) It runs indefinitely until a condition is met

Answer: a) It executes a block of code once for each item in a vector or list
Explanation: A for loop iterates over each element in a vector or list and executes the associated block of code for each element.


36.                     What will the following R code output?

r

CopyEdit

ifelse(3 > 2, "Yes", "No")

a) Yes
b) No
c) TRUE
d) Error

Answer: a) Yes
Explanation: The ifelse() function checks the condition (if 3 is greater than 2) and returns "Yes" since the condition is true.


37.                     How can you access the first element of a vector v in R?

a) v(1)
b) v[1]
c) v{1}
d) v{0}

Answer: b) v[1]
Explanation: In R, you can access an element of a vector by using square brackets and the index of the element.


38.                     Which of the following is the correct way to define a vector of numbers from 1 to 5 in R?

a) c(1, 2, 3, 4, 5)
b) range(1, 5)
c) vector(1, 5)
d) seq(1, 5)

Answer: a) c(1, 2, 3, 4, 5)
Explanation: The c() function combines numbers into a vector.


39.                     Which of the following will create a list in R?

a) list(1, 2, 3)
b) c(1, 2, 3)
c) matrix(1, 2, 3)
d) array(1, 2, 3)

Answer: a) list(1, 2, 3)
Explanation: The list() function creates a list, which can contain various types of objects.


40.                     What is the output of the following R expression?

r

CopyEdit

x <- c(2, 4, 6)

y <- c(1, 2, 3)

x + y

a) c(3, 6, 9)
b) c(2, 4, 6)
c) c(1, 2, 3)
d) Error

Answer: a) c(3, 6, 9)
Explanation: R performs vectorized operations, so x + y adds corresponding elements of x and y resulting in c(3, 6, 9).


41.                     Which function can be used to get the length of a vector in R?

a) length()
b) size()
c) count()
d) measure()

Answer: a) length()
Explanation: The length() function returns the number of elements in a vector.


42.                     What will the following R code output?

r

CopyEdit

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

v[v > 25]

a) 10 20
b) 30 40 50
c) 20 30 40 50
d) 10 50

Answer: b) 30 40 50
Explanation: The condition v > 25 selects all elements greater than 25, which are 30, 40, and 50.


43.                     What is the purpose of the repeat loop in R?

a) It runs a block of code indefinitely until a condition is met.
b) It runs a block of code for a fixed number of times.
c) It performs an action once based on a condition.
d) It repeats the last executed code block.

Answer: a) It runs a block of code indefinitely until a condition is met.
Explanation: The repeat loop runs indefinitely unless explicitly stopped by a break statement.


44.                     Which function is used to create a sequence of numbers in R?

a) sequence()
b) seq()
c) vector()
d) range()

Answer: b) seq()
Explanation: The seq() function generates sequences of numbers with specified intervals.


45.                     What is the output of this R code?

r

CopyEdit

x <- 4

y <- 5

if (x == y) {

    print("Equal")

} else {

    print("Not Equal")

}

a) Equal
b) Not Equal
c) Error
d) Nothing

Answer: b) Not Equal
Explanation: Since x is not equal to y, the condition evaluates to false and "Not Equal" is printed.


46.                     Which of the following is used to apply a function to each element of a list or vector in R?

a) lapply()
b) apply()
c) sapply()
d) All of the above

Answer: d) All of the above
Explanation: lapply(), apply(), and sapply() are all functions used to apply a given function over a list, vector, or other objects in R.


47.                     What is the output of the following R expression?

r

CopyEdit

sum(1:5)

a) 5
b) 10
c) 15
d) 1

Answer: c) 15
Explanation: The sum(1:5) adds the numbers from 1 to 5: 1 + 2 + 3 + 4 + 5 = 15.


48.                     What is the result of c(TRUE, FALSE) & c(FALSE, TRUE) in R?

a) TRUE FALSE
b) FALSE FALSE
c) TRUE TRUE
d) FALSE TRUE

Answer: b) FALSE FALSE
Explanation: The & operator performs element-wise logical AND. TRUE & FALSE gives FALSE, and FALSE & TRUE also gives FALSE.


49.                     Which of the following is the correct syntax for defining a function in R?

a) function name() { code }
b) function(name) { code }
c) name <- function() { code }
d) def name() { code }

Answer: c) name <- function() { code }
Explanation: In R, a function is defined using the function() keyword, and it is assigned to a variable using <-.


50.                     Which of the following is used to stop the execution of a loop prematurely in R?

a) exit
b) stop()
c) break
d) continue

Answer: c) break
Explanation: The break statement is used to exit a loop prematurely in R.


 

No comments:

Post a Comment