is the built-in R constant that represents a missing value in
datasets.
NA (or NA)
is R’s primary data structure for tabular data, consisting of a list of
equal-length vectors.
Data frame (or data.frame)
is the operator used for matrix multiplication in R.
%*%
is the R function used to determine the internal storage type of an
object.
typeof()
is the R6 class operation that removes and returns the top item
from a stack ADT.
pop (or pop())
R is a compiled language that requires code to be translated into machine
code before execution.
In R, variable names can start with a number or an underscore.
FALSE — Variable names cannot start with a number or underscore (underline
“can”)
The next statement in R skips the current iteration of a loop and proceeds to
the next iteration.
TRUE
R uses lexical scoping, meaning variables are looked up based on how
functions are nested in the code.
TRUE
The double square brackets [[]] are used for subsetting vectors and returning
multiple elements.
FALSE — Double square brackets [[]] extract single elements from lists
(underline “multiple”)
Write an R function named calculate_bmi() that:
● Accepts two parameters: weight_kg (numeric) and height_cm (numeric)
● Calculates BMI using the formula: BMI = weight_kg / (height_m)^2, where
height_m = height_cm/100
● Returns the BMI value rounded to 2 decimal places
● Includes a default value of 70 for weight_kg and 175 for height_cm
calculate_bmi <- function(weight_kg = 70, height_cm = 175) {
height_m <- height_cm / 100
bmi <- weight_kg / (height_m^2)
return(round(bmi, 2))
}
Analyze the following R code and determine what will be printed:
x <- c(TRUE, FALSE, TRUE, FALSE)
y <- c(TRUE, TRUE, FALSE, FALSE)
result <- x & y
print(result)
[1] TRUE FALSE FALSE FALSE
Write a for loop that calculates the sum of all even numbers from 1 to 20 and prints the
final sum.
sum_even <- sum(seq(2, 20, 2))
print(paste(“Sum of even numbers from 1 to 20:”, sum_even))
Or
sum_even <- 0
for (i in 1:20) {
if (i %% 2 == 0) {
sum_even <- sum_even + i
}
}
Print (sum)
Given the following data frame:
students <- data.frame(
id = 1:5,
name = c(“Ana”, “Ben”, “Carla”, “David”, “Elena”),
score = c(92, 67, 78, 45, 88),
stringsAsFactors = FALSE
)
Write R code to:
● Add a new column named status
● Assign “Pass” if score is ≥ 75, otherwise assign “Fail”
● Display only the name, score, and status columns for students who passed
students$status <- ifelse(students$score >= 75, “Pass”, “Fail”)
students[students$status == “Pass”, c(“name”, “score”, “status”)]
Write a recursive function named factorial() that calculates the factorial of a non-negative
integer n (n! = n × (n-1) × … × 1). Test your function with n = 6.
factorial <- function(n) {
if (n <= 1) {
return(1)
} else {
return(n * factorial(n - 1))
}
}