R Quiz - MCQ - Multiple Choice Questions

Welcome to the R programming Quiz. Here, you can find 50+ multiple-choice questions (MCQs) covering various aspects of the R programming language. These questions span a wide range of topics within R, including fundamental concepts, syntax, functions, data types, and specific programming practices. Each question is formulated to test understanding and proficiency in R programming, making this collection suitable for learners at different levels, from beginners to intermediate users. The questions also come with answers and brief explanations to reinforce learning and provide insight into the reasoning behind the correct choices.

This set encompasses questions on basic operations, vector manipulation, data frames, functions, control structures, and statistical operations, among others. It's designed to serve as a comprehensive resource for self-assessment, educational purposes, exam preparation, or even as a teaching aid. Whether you're looking to test your understanding of R, prepare for an exam, or construct an educational activity, these MCQs offer a broad overview of the language's capabilities and common programming patterns encountered in data analysis and statistical computing with R.

1. What is the use of the c() function in R?

a) To create a conditional statement
b) To combine values into a vector or list
c) To clear the console
d) To compute the cosine of a number

Answer:

b) To combine values into a vector or list

Explanation:

The c() function in R is used to combine values into a vector or list. It's a fundamental function for creating vectorized data structures.

2. How do you check the structure of an object in R?

a) obj()
b) structure()
c) str()
d) typeof()

Answer:

c) str()

Explanation:

The str() function is used to display the structure of an R object, providing a compact, human-readable summary of its type, length, and content.

3. Which of the following is used to install packages in R?

a) include()
b) library()
c) require()
d) install.packages()

Answer:

d) install.packages()

Explanation:

The install.packages() function is used to download and install packages from CRAN, making them available for use in R.

4. What does the lapply() function do?

a) Applies a function over a list and returns a list
b) Applies a function to each row of a dataframe
c) Linear approximation
d) Lazy evaluation of an expression

Answer:

a) Applies a function over a list and returns a list

Explanation:

The lapply() function in R applies a function to each element of a list or vector and returns a list of the same length.

5. How do you create a dataframe in R?

a) dataframe()
b) as.dataframe()
c) data.frame()
d) create.df()

Answer:

c) data.frame()

Explanation:

The data.frame() function is used to create dataframes in R. Dataframes are used to store tabular data where each column can contain elements of the same or different types.

6. Which function is used to read a CSV file into R?

a) read.csv()
b) read_csv()
c) load.csv()
d) import.csv()

Answer:

a) read.csv()

Explanation:

The read.csv() function is used to read a file in CSV (comma-separated values) format and create a dataframe in R.

7. What symbol is used to assign a value to a variable in R?

a) =
b) :=
c) <-
d) <<

Answer:

c) <-

Explanation:

In R, the <- i=""> symbol is commonly used for assignment, though = can also be used for the same purpose in many contexts.

8. Which function can be used for generating sequence of numbers in R?

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

Answer:

a) seq()

Explanation:

The seq() function is used to generate sequences of numbers in R. It is highly flexible, allowing specification of start, end, and step values.

9. What does the ggplot2 package in R primarily provide?

a) Advanced mathematical functions
b) Data manipulation capabilities
c) Tools for creating data visualizations
d) Database connection utilities

Answer:

c) Tools for creating data visualizations

Explanation:

The ggplot2 package is a popular system for creating data visualizations in R, based on the Grammar of Graphics.

10. Which of the following functions is used to apply a function to each column of a dataframe or matrix?

a) lapply()
b) sapply()
c) apply()
d) colApply()

Answer:

c) apply()

Explanation:

The apply() function is used to apply a function to the rows or columns of a matrix or dataframe in R. It is versatile and can operate over arrays as well.

11. How do you subset a dataframe in R based on condition?

a) subset(df, condition)
b) df[condition]
c) df$column[condition]
d) filter(df, condition)

Answer:

a) subset(df, condition)

Explanation:

The subset() function is used for subsetting a dataframe based on a specified condition, making it straightforward to filter rows.

12. What is the output type of the summary() function when applied to a dataframe?

a) A detailed report in the console
b) Another dataframe
c) A list containing summary statistics for each column
d) A numeric vector

Answer:

c) A list containing summary statistics for each column

Explanation:

When applied to a dataframe, the summary() function returns a list that includes summary statistics such as the mean, median, and quartiles for each column.

13. Which package in R is most commonly used for data manipulation?

a) shiny
b) ggplot2
c) dplyr
d) tidyr

Answer:

c) dplyr

Explanation:

The dplyr package is widely used for data manipulation in R, providing a consistent set of verbs that help in simplifying data manipulation challenges.

14. How can you create a scatter plot in R?

a) plot(x, y, type = "s")
b) plot(x, y, type = "b")
c) plot(x, y, type = "p")
d) plot(x, y, type = "l")

Answer:

c) plot(x, y, type = "p")

Explanation:

The plot() function with type set to "p" creates a scatter plot, where "p" stands for 'points'.

15. What does the t() function perform on a matrix in R?

a) Transforms its values
b) Truncates its dimensions
c) Transposes it
d) Tests its type

Answer:

c) Transposes it

Explanation:

The t() function transposes a matrix in R, flipping its rows and columns.

16. Which of the following is NOT a valid variable name in R?

a) .varName
b) _varName
c) var.Name
d) varName1

Answer:

b) _varName

Explanation:

Variable names in R can start with a letter or a dot, but if it starts with a dot, it cannot be followed by a number. An underscore is not a valid starting character for a variable name in R.

17. Which data type does NOT exist in R?

a) Character
b) Integer
c) Short
d) Complex

Answer:

c) Short

Explanation:

R supports several data types, including character, integer, and complex, but it does not have a data type specifically called 'short'.

18. How do you concatenate two strings in R?

a) concat(str1, str2)
b) paste(str1, str2)
c) str1 + str2
d) join(str1, str2)

Answer:

b) paste(str1, str2)

Explanation:

The paste() function is used to concatenate strings in R. It can combine multiple strings into one and also allows for the inclusion of a separator.

19. How can you define a function in R that calculates the square of a number?

a) square <- function(x) { return x^2 }
b) function square(x) = x^2
c) def square(x): return x**2
d) square(x): x^2

Answer:

a) square <- function(x) { return x^2 }

Explanation:

In R, functions are defined using the function keyword, with arguments inside parentheses, followed by the body of the function enclosed in curly braces.

20. Which loop structure is NOT present in R?

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

Answer:

c) do-while

Explanation:

R supports for, while, and repeat loops for iteration, but it does not have a do-while loop structure.

21. Which function is used to create a list containing elements of different types in R?

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

Answer:

c) list()

Explanation:

The list() function is used to create lists in R. Unlike vectors, lists can hold elements of different types.

22. How do you define an array with 2 rows and 3 columns in R?

a) array(1:6, dim = c(2, 3))
b) matrix(1:6, nrow = 2, ncol = 3)
c) dataframe(1:6, rows = 2, cols = 3)
d) vector(1:6, length = 6)

Answer:

a) array(1:6, dim = c(2, 3))

Explanation:

An array in R can be created using the array() function, where the dim argument specifies the dimensions of the array.

23. What function do you use to add a column to a dataframe in R?

a) append()
b) attach()
c) cbind()
d) merge()

Answer:

c) cbind()

Explanation:

The cbind() function is used to combine objects by columns, which makes it suitable for adding a new column to a dataframe in R.

24. How do you access the third element of a vector in R?

a) vector[3]
b) vector(3)
c) get(vector, 3)
d) vector.third

Answer:

a) vector[3]

Explanation:

In R, elements of a vector are accessed using square brackets and the index of the element, with indexing starting at 1.

25. Which of the following is true about R lists?

a) Lists in R can only hold elements of the same type.
b) Lists in R are a type of vector.
c) Lists in R cannot contain other lists.
d) Lists in R can hold elements of different types.

Answer:

d) Lists in R can hold elements of different types.

Explanation:

Lists are a versatile data structure in R that can contain elements of different types, including numbers, strings, vectors, and even other lists.

26. What is the result of combining a vector of characters and a vector of numbers with the c() function?

a) A vector of characters
b) A vector of numbers
c) An error
d) A list

Answer:

a) A vector of characters

Explanation:

When combining characters and numbers using the c() function, the numbers are coerced into characters, resulting in a character vector.

27. In R, what is the purpose of the NA value?

a) It represents a missing or undefined value.
b) It is a placeholder for future assignment.
c) It denotes a null pointer or reference.
d) It is used to terminate loops prematurely.

Answer:

a) It represents a missing or undefined value.

Explanation:

NA is used in R to represent missing or undefined data. It can appear in any type of vector.

28. Which function allows you to apply a function conditionally across elements of a list in R?

a) lapply()
b) sapply()
c) apply()
d) ifelse()

Answer:

d) ifelse()

Explanation:

The ifelse() function evaluates a condition and applies the first function to elements where the condition is true and the second function where it is false. It is vectorized and can be used with lists by applying it within an lapply() or sapply() function.

29. How do you remove NA values from a vector in R?

a) na.omit(vector)
b) vector[!is.na(vector)]
c) remove.na(vector)
d) vector[-na]

Answer:

b) vector[!is.na(vector)]

Explanation:

To remove NA values from a vector, you can subset the vector by negating the is.na() function, which identifies NA values.

30. What is the default mode of a vector created by the vector() function without specifying the mode?

a) numeric
b) character
c) logical
d) integer

Answer:

a) numeric

Explanation:

If you do not specify the mode when creating a vector with the vector() function, it defaults to numeric mode.

31. Which R operator is used for element-wise multiplication of two vectors?

a) *
b) %*%
c) ^
d) %/%

Answer:

a) *

Explanation:

The * operator performs element-wise multiplication of vectors in R, multiplying each corresponding pair of elements from the two vectors.

32. What is the primary way to handle exceptions in R?

a) try-catch blocks
b) if-else statements
c) stop() function
d) try() function

Answer:

d) try() function

Explanation:

The try() function is used in R to handle exceptions, allowing execution to continue even if an error occurs.

33. How do you split a string into individual characters in R?

a) split(str, "")
b) strsplit(str, "")
c) separate(str, "")
d) chars(str)

Answer:

b) strsplit(str, "")

Explanation:

The strsplit() function is used to split strings in R, and providing an empty string as the split parameter splits the string into individual characters.

34. Which R function is used to check if a value is NA?

a) is.na(value)
b) is.null(value)
c) is.missing(value)
d) is.undefined(value)

Answer:

a) is.na(value)

Explanation:

The is.na() function is used to test for missing values (NA) in R. It returns TRUE if the value is NA and FALSE otherwise.

35. How can you repeat a vector c(1,2,3) three times in R?

a) rep(c(1,2,3), times=3)
b) repeat(c(1,2,3), 3)
c) cycle(c(1,2,3), 3)
d) loop(c(1,2,3), 3)

Answer:

a) rep(c(1,2,3), times=3)

Explanation:

The rep() function repeats the elements of vectors and lists, and the times argument specifies how many times to repeat the vector.

36. What is the purpose of the set.seed() function in R?

a) It initializes the random number generator to a specific state.
b) It creates a unique identifier for each session.
c) It seeds the environment with variables.
d) It determines the precision of floating-point operations.

Answer:

a) It initializes the random number generator to a specific state.

Explanation:

set.seed() is used to initialize R's random number generator to a specific state, ensuring reproducibility of code that generates random numbers.

37. Which statement creates a factor in R with three levels?

a) factor(c("low", "medium", "high"))
b) c("low", "medium", "high")
c) list("low", "medium", "high")
d) array(c("low", "medium", "high"))

Answer:

a) factor(c("low", "medium", "high"))

Explanation:

The factor() function is used to encode a vector as a factor, which is useful for categorical data with a fixed number of possible values, or levels.

38. How do you convert a factor to a numeric vector in R?

a) as.numeric(as.character(factor))
b) numeric(factor)
c) to.numeric(factor)
d) convert(factor, "numeric")

Answer:

a) as.numeric(as.character(factor))

Explanation:

Converting a factor to a numeric vector directly with as.numeric() converts the factor levels to their internal codes. To convert based on the factor's labels, you should first convert it to character with as.character() and then to numeric.

39. In R, which function can be used to merge two data frames by a common column?

a) merge(df1, df2, by="commonColumn")
b) concatenate(df1, df2, on="commonColumn")
c) join(df1, df2, key="commonColumn")
d) bind(df1, df2, together="commonColumn")

Answer:

a) merge(df1, df2, by="commonColumn")

Explanation:

The merge() function merges two data frames by common columns or row names, specified by the by argument.

40. How is a comment indicated in R code?

a) #
b) //
c) /*
d) --

Answer:

a) #

Explanation:

In R, comments are indicated by the # symbol. Everything following # on the line is treated as a comment.

41. Which of the following is a valid way to declare a matrix with 2 rows and 3 columns filled with zeros?

a) matrix(0, nrow=2, ncol=3)
b) zeros(2,3)
c) matrix([0,0,0,0,0,0], nrow=2)
d) array(0, dim=c(2,3))

Answer:

a) matrix(0, nrow=2, ncol=3)

Explanation:

The matrix() function creates a matrix, and its first argument specifies the data to fill the matrix, followed by the nrow and ncol arguments to specify the number of rows and columns.

42. What is the result of the expression is.vector(list(1,2,3)) in R?

a) TRUE
b) FALSE
c) Error
d) NULL

Answer:

b) FALSE

Explanation:

A list is not considered a vector in R in the context of is.vector(), which checks for atomic vectors. Although technically a list is a generic vector, this function specifically returns FALSE for lists.

43. How can you save the workspace at the end of an R session?

a) save.workspace()
b) save.session()
c) save.image()
d) save.env()

Answer:

c) save.image()

Explanation:

The save.image() function saves the current R workspace to a file, typically called ".RData", allowing you to restore it in future sessions.

44. Which of the following functions can be used to generate a sequence that progresses from 1 to 10 in steps of 2 in R?

a) seq(1, 10, by=2)
b) sequence(1, 10, step=2)
c) generate(1, 10, 2)
d) range(1, 10, increment=2)

Answer:

a) seq(1, 10, by=2)

Explanation:

The seq() function in R is used to generate sequences. The by argument specifies the increment between each number in the sequence.

45. How do you create a matrix in R where the numbers 1 through 9 are arranged in 3 rows and 3 columns?

a) matrix(1:9, nrow=3, ncol=3)
b) array(1:9, dim=c(3,3))
c) build.matrix(1:9, rows=3, columns=3)
d) cbind(1:3, 4:6, 7:9)

Answer:

a) matrix(1:9, nrow=3, ncol=3)

Explanation:

The matrix() function creates a matrix from the given set of values. The nrow and ncol parameters define the number of rows and columns.

46. What does the dim() function return when applied to a dataframe in R?

a) The number of elements in the dataframe
b) The number of columns in the dataframe
c) A vector containing the number of rows and columns
d) The length of the dataframe

Answer:

c) A vector containing the number of rows and columns

Explanation:

The dim() function, when applied to a dataframe, returns a vector of length 2 indicating the number of rows and columns in the dataframe.

47. Which of the following syntaxes removes a variable from the R environment?

a) del(var)
b) unset(var)
c) remove(var)
d) rm(var)

Answer:

d) rm(var)

Explanation:

The rm() function is used to remove objects, such as variables, from the R environment.

48. Which function is used to round numbers to the nearest integer in R?

a) round()
b) int()
c) floor()
d) ceil()

Answer:

a) round()

Explanation:

The round() function rounds values to the nearest integer. floor() rounds down, and ceil() rounds up, while int() is not a standard rounding function in R.

49. How do you calculate the mean of a numeric vector in R?

a) mean(vector)
b) average(vector)
c) sum(vector) / length(vector)
d) median(vector)

Answer:

a) mean(vector)

Explanation:

The mean() function calculates the arithmetic mean of a numeric vector. While sum(vector) / length(vector) could also work, mean() is the direct and preferred method.

50. Which statement is used to import the ggplot2 library in an R script?

a) import ggplot2
b) include("ggplot2")
c) library(ggplot2)
d) use ggplot2

Answer:

c) library(ggplot2)

Explanation:

The library() function is used to load and attach add-on packages. library(ggplot2) makes the functions and data in ggplot2 available for use.

51. What is the result of executing is.logical(c(TRUE, FALSE)) in R?

a) TRUE
b) FALSE
c) Error
d) NULL

Answer:

b) FALSE

Explanation:

is.logical() checks if an object is a logical vector. While c(TRUE, FALSE) is indeed a logical vector, is.logical() checks for the object type, not its content, and a general vector, even solely containing logical values, is considered just a vector, not specifically a logical vector by this function.

52. How do you subset a dataframe df to only include rows where the value of the column age is greater than 30?

a) df[df$age > 30, ]
b) subset(df, age > 30)
c) df[which(df$age > 30)]
d) Both a) and b) are correct.

Answer:

d) Both a) and b) are correct.

Explanation:

Both the bracket notation with a condition df[df$age > 30, ] and the subset() function subset(df, age > 30) can be used to subset a dataframe based on a condition.

53. In R, how can you generate a random sample of 3 numbers from the vector c(1,2,3,4,5)?

a) sample(c(1,2,3,4,5), 3)
b) random(c(1,2,3,4,5), 3)
c) choose(c(1,2,3,4,5), 3)
d) pick(c(1,2,3,4,5), 3)

Answer:

a) sample(c(1,2,3,4,5), 3)

Explanation:

The sample() function is used for random sampling. Here, it selects 3 random numbers from the provided vector.

54. What does the rnorm() function generate in R?

a) A sequence of rational numbers
b) A random permutation of numbers
c) A vector of random numbers following a normal distribution
d) A repeat sequence of numbers

Answer:

c) A vector of random numbers following a normal distribution

Explanation:

The rnorm() function generates random numbers from a normal distribution, with arguments to specify the number of observations, mean, and standard deviation.

55. Which keyword is used to define a global variable inside a function in R?

a) global
b) <<-
c) ::
d) globalVar

Answer:

b) <<-

Explanation:

The <<- operator is used to assign a value to a global variable from within a function, altering the variable outside of the function's scope.

Comments