
















































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!

















































Question 1. Which function is used to obtain the documentation for a specific R object? A) help() B) example() C)? D) source() Answer: C Explanation: The “?” operator is a shortcut for help() and displays the documentation page for the given object. Question 2. What does the command setwd("C:/Data") accomplish? A) Sets the working directory to “C:/Data” B) Saves the current workspace to “C:/Data” C) Changes the default library path to “C:/Data” D) Lists all files in “C:/Data” Answer: A Explanation: setwd() changes the R session’s working directory to the specified path. Question 3. In R, which of the following is a reserved keyword that cannot be used as a variable name? A) mydata B) data.frame C) mean D) TRUE Answer: D Explanation: TRUE is a logical constant in R and is reserved; it cannot be redefined as a variable. Question 4. Which operator creates a sequence from 1 to 10 in R? A) seq(1,10) B) 1:10 C) c(1,10) D) rep(1,10) Answer: B Explanation: The colon operator : generates integer sequences directly. Question 5. What is the result of 3 %% 2 in R? A) 1 B) 0 C) 1.5 D) 2 Answer: A Explanation: The modulus operator %% returns the remainder; 3 divided by 2 leaves remainder 1.
Question 6. Which of the following statements about the numeric vector v <- c(1, 2, 3) is FALSE? A) class(v) returns "numeric" B) typeof(v) returns "double" C) is.integer(v) returns TRUE D) length(v) returns 3 Answer: C Explanation: By default, numeric literals are of type double, not integer; is.integer(v) is FALSE. Question 7. How can you create a matrix with 3 rows and 2 columns filled by column from the vector 1:6? A) matrix(1:6, nrow=3, ncol=2, byrow=TRUE) B) matrix(1:6, nrow=3, ncol=2) C) matrix(1:6, nrow=2, ncol=3) D) array(1:6, dim=c(3,2)) Answer: B Explanation: The default filling order for matrix() is column‑wise; byrow=FALSE (default) yields the desired matrix. Question 8. Which function converts a character vector to a factor? A) as.numeric() B) factor() C) as.character() D) levels() Answer: B Explanation: factor() creates a factor from a character (or numeric) vector, assigning levels. Question 9. Given df <- data.frame(x=1:3, y=c("a","b","c")), what does df$x[2] return? A) 2 B) "b" C) "a" D) NA Answer: A Explanation: $x selects column x (numeric 1:3); indexing with [2] returns the second element, 2.
Explanation: apply(X, MARGIN, FUN) uses MARGIN to indicate rows (1) or columns (2). Question 15. What does the expression ifelse(x > 0, "pos", "non‑pos") return when x is a vector? A) A single string indicating the overall condition B) A vector of the same length as x with element‑wise results C) An error because ifelse works only with scalars D) NULL Answer: B Explanation: ifelse is vectorised; it evaluates the test for each element and returns a vector of results. Question 16. Which function from the stringr package extracts the first three characters of each string in a vector v? A) str_sub(v, 1, 3) B) substr(v, 1, 3) C) str_extract(v, "^.{3}") D) Both A and C Answer: D Explanation: str_sub() and str_extract() with a regex both retrieve the first three characters. Question 17. In the dplyr package, which verb adds new columns based on existing ones? A) filter() B) select() C) mutate() D) arrange() Answer: C Explanation: mutate() creates or transforms columns while preserving all existing data. Question 18. Which function from the lubridate package parses the character string “2023‑ 04 ‑ 15 14:30” into a POSIXct date‑time object? A) ymd_hm("2023‑ 04 ‑15 14:30") B) dmy_hms("2023‑ 04 ‑15 14:30") C) ymd_hms("2023‑ 04 ‑ 15 14:30") D) mdy_hm("2023‑ 04 ‑15 14:30") Answer: A Explanation: ymd_hm() expects year‑month‑day and hour‑minute, matching the supplied format.
Question 19. Which of the following statements correctly reads a CSV file named “data.csv” while treating strings as characters (not factors)? A) read.csv("data.csv", stringsAsFactors = FALSE) B) read.csv("data.csv", factor = FALSE) C) read.table("data.csv", stringsAsFactors = TRUE) D) read.csv2("data.csv") Answer: A Explanation: stringsAsFactors = FALSE prevents automatic conversion of character columns to factors. Question 20. What does the pipe operator %>% from the magrittr package do? A) Assigns the left‑hand object to the right‑hand variable B) Passes the left‑hand output as the first argument to the right‑hand function C) Creates a list of the two objects D) Performs element‑wise multiplication Answer: B Explanation: %>% forwards the left‑hand side as the first argument to the function on the right, enabling readable chains. Question 21. Which function from the DBI package establishes a connection to a SQLite database file named “mydb.sqlite”? A) dbConnect(RSQLite::SQLite(), dbname = "mydb.sqlite") B) dbConnect(SQLite(), "mydb.sqlite") C) dbConnect(RSQLite, path = "mydb.sqlite") D) dbConnect(RSQLite, db = "mydb.sqlite") Answer: A Explanation: dbConnect(RSQLite::SQLite(), dbname = "mydb.sqlite") correctly creates a SQLite connection. Question 22. In base R graphics, which function creates a histogram of the variable age? A) hist(age) B) plot(age) C) barplot(age) D) boxplot(age) Answer: A Explanation: hist() is specifically designed to produce histograms of numeric data. Question 23. Which ggplot2 aesthetic maps a variable to point colour?
Explanation: traceback() prints the sequence of calls that led to the error. Question 28. What is the purpose of the Rprof() function? A) To profile memory usage of objects B) To collect timing information for each line of R code C) To generate a summary of package dependencies D) To export the current workspace to a file Answer: B Explanation: Rprof() records CPU usage per expression, allowing performance analysis. Question 29. Which of the following is NOT a valid way to subset rows 2 through 5 of a data frame df? A) df[2:5, ] B) df[2:5] C) df[2:5, , drop = FALSE] D) df[2:5, , drop = TRUE] Answer: B Explanation: df[2:5] selects columns 2 through 5, not rows; row subsetting requires a comma. Question 30. Which function from the jsonlite package converts a JSON string to an R list? A) fromJSON() B) toJSON() C) jsonParse() D) parseJSON() Answer: A Explanation: fromJSON() parses JSON text and returns the corresponding R object. Question 31. In base R, what does the expression x[!is.na(x)] accomplish? A) Replaces NA values with zero B) Returns all non‑missing values of x C) Converts NA to the string “NA” D) Generates an error if x contains NA Answer: B Explanation: !is.na(x) creates a logical vector that is TRUE for non‑missing entries; subsetting with it extracts those values.
Question 32. Which of the following statements about the %in% operator is TRUE? A) It returns the positions of matching elements. B) It checks for exact matches and returns a logical vector. C) It performs a set union. D) It is equivalent to the match() function. Answer: B Explanation: %in% tests membership and returns TRUE/FALSE for each element of the left operand. Question 33. What does the str() function display for an object? A) The object's class only B) The internal memory address C) A compact, human‑readable summary of its structure D) The source code that created the object Answer: C Explanation: str() provides a concise overview of an object’s type, dimensions, and first few elements. Question 34. Which R function can be used to compute the correlation matrix of a numeric data frame df? A) cov(df) B) cor(df) C) summary(df) D) var(df) Answer: B Explanation: cor() calculates pairwise Pearson (or other) correlations for numeric columns. Question 35. Which of the following is the correct syntax to create a factor with ordered levels “low”, “medium”, “high”? A) factor(c("low","medium","high"), ordered = TRUE) B) ordered(c("low","medium","high")) C) factor(c("low","medium","high"), levels = c("low","medium","high"), ordered = TRUE) D) factor(c("low","medium","high"), ordered = FALSE) Answer: C
Answer: A Explanation: install.packages() downloads and installs a package; library() only loads it. Question 40. In R, which function returns the current date as an object of class “Date”? A) Sys.time() B) Sys.Date() C) today() D) date() Answer: B Explanation: Sys.Date() returns the current calendar date without time components. Question 41. Which of the following ggplot2 geoms is used to create a box‑and‑whisker plot? A) geom_line() B) geom_boxplot() C) geom_histogram() D) geom_point() Answer: B Explanation: geom_boxplot() draws box‑and‑whisker plots to visualise distributions. Question 42. What does the options(stringsAsFactors = FALSE) command change globally? A) It prevents automatic conversion of strings to factors when creating data frames. B) It forces all character vectors to be stored as factors. C) It disables the use of strings in the R console. D) It changes the default printing of strings. Answer: A Explanation: Setting stringsAsFactors = FALSE globally stops the default factor conversion for character columns. Question 43. Which of the following functions can be used to read an Excel sheet named “Sheet1” from the file “sales.xlsx”? A) read_excel("sales.xlsx", sheet = "Sheet1") B) read.csv("sales.xlsx", sheet = 1) C) read_excel("sales.xlsx", 1) D) read.table("sales.xlsx") Answer: A Explanation: read_excel() from the readxl package reads Excel files; the sheet argument specifies the sheet name.
Question 44. In a Shiny app, which function is used to define the server‑side logic? A) ui() B) server() C) shinyApp() D) runApp() Answer: B Explanation: The server function contains reactive expressions and output renderings; ui defines the user interface. Question 45. Which of the following correctly extracts the month component from a POSIXct date dt using base R? A) months(dt) B) format(dt, "%m") C) month(dt) D) as.month(dt) Answer: B Explanation: format() with “%m” returns the month as a character string; months() returns the month name but not the numeric month. Question 46. What does the duplicated() function return when applied to a vector? A) A logical vector indicating which elements are duplicates of previous elements B) The number of duplicate elements C) The indices of all duplicate elements D) A vector with duplicates removed Answer: A Explanation: duplicated(x) flags TRUE for elements that have appeared earlier in the vector. Question 47. Which of the following is the correct syntax to define a function square that returns the square of its argument x? A) square <- function(x) { return(x^2) } B) function square(x) { x*x } C) square(x) <- x^2 D) square = function(x) x^2; return(square) Answer: A Explanation: The standard function definition uses function(x) and optionally return(). Question 48. In the apply() family, which function always returns a list regardless of the input?
Explanation: The alpha aesthetic sets the opacity level of geoms. Question 53. Which of the following expressions will correctly assign the value 10 to a variable named x inside a function without affecting a global variable of the same name? A) x <- 10 B) assign("x", 10, envir = parent.frame()) C) assign("x", 10, envir = .GlobalEnv) D) local({x <- 10}) Answer: D Explanation: local({x <- 10}) creates a temporary environment; the assignment does not leak to the global environment. Question 54. Which of the following is the most efficient way to calculate the cumulative sum of a numeric vector v? A) for(i in 2:length(v)) v[i] <- v[i] + v[i-1] B) cumsum(v) C) Reduce(+, v, accumulate = TRUE) D) sapply(seq_along(v), function(i) sum(v[1:i])) Answer: B Explanation: cumsum() is a vectorised, built‑in function optimized for cumulative sums. Question 55. In dplyr, which verb would you use to reorder rows based on a variable score in descending order? A) arrange(desc(score)) B) order_by(score, descending = TRUE) C) sort(score, decreasing = TRUE) D) rank(-score) Answer: A Explanation: arrange(desc(score)) orders rows by score from highest to lowest. Question 56. Which of the following methods can be used to create a reproducible random sample in R? A) set.seed(123); sample(1:10, 5) B) sample(1:10, 5, replace = TRUE) C) runif(5) D) set.seed(); sample(1:10, 5) Answer: A Explanation: set.seed() initializes the random number generator, ensuring reproducibility.
Question 57. Which of the following functions from the rvest package extracts all hyperlinks (`` tags) from a web page object page? A) html_nodes(page, "a") B) html_links(page) C) html_anchor(page) D) html_all(page, "a") Answer: A Explanation: html_nodes() selects nodes matching a CSS selector; "a" selects hyperlink tags. Question 58. Which of the following statements about the :: operator is correct? A) It accesses a hidden object inside a package. B) It loads a package into the session. C) It extracts a function from a specific package without attaching the package. D) It creates a new namespace. Answer: C Explanation: package::function accesses a function from a package without attaching the whole package. Question 59. What does the summary() function return when applied to a factor variable? A) The numeric codes of the factor levels B) The count of each level (frequency table) C) The underlying character vector D) NULL Answer: B Explanation: summary() on a factor produces a table of frequencies for each level. Question 60. Which of the following is the correct way to suppress warnings for a specific expression in R? A) suppressWarnings(expr) B) warning(expr) C) tryCatch(expr, warning = function(w) NULL) D) both A and C Answer: D Explanation: Both suppressWarnings() and a tryCatch handling of warnings can silence them.
B) Whether two objects are exactly the same, including attributes and types C) Whether two numeric vectors have the same length D) Whether two data frames have identical column names Answer: B Explanation: identical() returns TRUE only if the objects are indistinguishable in every aspect. Question 66. Which of the following statements about the ... (ellipsis) argument in a function definition is FALSE? A) It allows the function to accept an arbitrary number of additional arguments. B) It can be passed on to other functions that also accept .... C) It must be placed as the first argument in the function signature. D) It can be used with list(...) to capture the extra arguments as a list. Answer: C Explanation: The ellipsis can appear anywhere in the argument list, not necessarily first. Question 67. Which of the following functions is used to compute the Euclidean distance matrix for a numeric matrix M? A) dist(M) B) euclidean(M) C) distance(M) D) cor(M) Answer: A Explanation: dist() computes pairwise distances; default method is Euclidean. Question 68. In ggplot2, which function adds a smooth conditional mean curve (e.g., LOESS) to a scatter plot? A) geom_smooth() B) stat_smooth() C) geom_line() D) Both A and B Answer: D Explanation: Both geom_smooth() and stat_smooth() add a smooth line; they are essentially the same. Question 69. Which of the following is the most appropriate way to write a comment that spans multiple lines in an R script?
A) /* comment */ B) # comment line 1 \n # comment line 2 C) # comment line 1; # comment line 2 D) Using triple quotes """ comment """ Answer: B Explanation: R uses # for comments; each line must start with #. There is no multi‑line comment syntax. Question 70. Which of the following functions from the caret package is used to split data into training and testing sets? A) createDataPartition() B) trainTestSplit() C) splitData() D) partition() Answer: A Explanation: createDataPartition() creates stratified splits for model training and testing. Question 71. Which of the following statements about the data.table package is TRUE? A) It provides the set() function for fast in‑place modification. B) [i, j, by] syntax is identical to dplyr verbs. C) It cannot handle large datasets efficiently. D) It replaces the need for any base R functions. Answer: A Explanation: data.table offers set() for efficient column updates without copying. Question 72. In base R, which function tests whether an object is a matrix? A) is.matrix() B) is.array() C) is.matrixic() D) is.vector() Answer: A Explanation: is.matrix() returns TRUE if the object has a matrix class. Question 73. Which of the following is the correct way to write a for‑loop that prints numbers 1 to 5? A) for(i in 1:5) print(i) B) for(i = 1; i <= 5; i++) print(i) C) while(i <=5) {print(i); i <- i+1} D) Both A and B Answer: D
Answer: D Explanation: map_chr() returns a character vector; map_dbl() returns a numeric vector. Question 79. Which of the following statements about the options() function is FALSE? A) It can set the number of printed digits via digits. B) It can change the default number of rows displayed with max.print. C) It permanently modifies the R installation. D) It returns a list of previous option values when a new value is supplied. Answer: C Explanation: options() only affects the current R session, not the installation. Question 80. In base R, which function would you use to compute the quantiles of a numeric vector x at probabilities 0, 0.25, 0.5, 0.75, and 1? A) quantile(x, probs = c(0, .25, .5, .75, 1)) B) summary(x) C) quantile(x) D) stats(x, probs = ...) Answer: A Explanation: quantile() with the probs argument returns the requested percentiles. Question 81. Which of the following statements about the caret function train() is TRUE? A) It automatically performs cross‑validation if a method argument is supplied. B) It only works with linear models. C) It cannot handle factor predictors. D) It does not provide model performance metrics. Answer: A Explanation: train() supports many modeling methods and can perform resampling (e.g., cross‑validation) based on the trainControl specification. Question 82. Which of the following is the correct way to convert a matrix m to a data frame while preserving row names as a column called “id”?
A) as.data.frame(m, row.names = "id") B) cbind(id = rownames(m), as.data.frame(m)) C) data.frame(id = rownames(m), m) D) Both B and C Answer: D Explanation: Both cbind() and data.frame() can prepend the row names as a new column. Question 83. Which of the following functions from the plotly package creates an interactive 3‑D scatter plot? A) plot_ly(type = "scatter3d") B) scatter3d() C) plot_ly3d() D) ggplotly() with geom_point3d() Answer: A Explanation: plot_ly() with type = "scatter3d" produces an interactive 3‑D scatter plot. Question 84. Which of the following statements about the readr package’s read_csv() function is FALSE? A) It automatically parses column types. B) It returns a tibble rather than a base data frame. C) It uses “;” as the default field separator. D) It provides progress bars for large files. Answer: C Explanation: read_csv() assumes commas as separators; read_delim() is used for other delimiters. Question 85. Which of the following base R functions can be used to compute the cumulative product of a numeric vector v? A) cumprod(v) B) prod(v) C) cumulate(v) D) cumsum(v) Answer: A Explanation: cumprod() returns the cumulative product; prod() gives the overall product. Question 86. In ggplot2, which function would you use to add a title to the plot? A) ggtitle() B) labs(title = "My Plot") C) theme(plot.title = element_text()) D) Both A and B Answer: D Explanation: Both ggtitle() and labs(title = …) add a main title.