Unit 12: R Tool - Subjective Questions
ECAP792 • Practice Questions with Detailed Answers
20 questions
Define R and explain its major features and applications in data science.
R is an open-source programming language and software environment designed for statistical computing, data analysis, and graphical visualization.
Major features:
- It is free, open-source, and available on Windows, Linux, and macOS.
- It provides extensive support for statistical tests, machine learning, and data visualization.
- Thousands of reusable packages are available through the Comprehensive R Archive Network (CRAN).
- It supports vectorized operations, reducing the need for explicit loops.
- It can import data from text files, spreadsheets, databases, and web-based sources.
- It produces publication-quality graphics through base R and packages such as ggplot2.
Applications in data science:
- Data cleaning and transformation
- Exploratory data analysis
- Statistical modeling
- Machine learning
- Data visualization
- Reproducible research and report generation
What is RStudio? Describe the main components of the RStudio interface.
RStudio is an integrated development environment (IDE) that provides tools for writing, executing, testing, and managing R programs. R is the programming language, while RStudio is an interface that makes working with R more convenient.
The main components are:
- Source pane: Used to create, edit, and save R scripts, R Markdown files, and other documents.
- Console pane: Executes R commands interactively and displays their output.
- Environment and History pane: The Environment tab displays current objects, while the History tab records previously executed commands.
- Files, Plots, Packages, Help, and Viewer pane: Used to browse files, inspect plots, manage packages, read documentation, and view web content.
RStudio also provides facilities for debugging, project management, code completion, version control, and reproducible report generation.
Distinguish between the R Console, an R script, and the R workspace.
The three terms represent different parts of an R working environment:
- R Console: An interactive area in which commands are entered and executed immediately. It is useful for quick calculations and experiments, but commands may be difficult to reuse unless saved elsewhere.
- R script: A text file, usually saved with the
.Rextension, containing a sequence of R statements. Scripts can be edited, documented, reused, and shared. - R workspace: The current collection of objects stored in memory, such as vectors, functions, matrices, and data frames.
ls()lists workspace objects, whilerm()removes selected objects.
For reproducible analysis, commands should normally be maintained in scripts rather than relying entirely on console history or a previously saved workspace.
Explain how packages are installed, loaded, inspected, and updated in R. Include suitable commands.
An R package is a collection of functions, datasets, and documentation created for a particular purpose.
- Install a package once from CRAN using
install.packages("ggplot2"). - Load it into the current session using
library(ggplot2). - View installed packages using
installed.packages(). - Update available packages using
update.packages(). - Open package documentation using
help(package = "ggplot2"). - Access a specific help page using
?function_name, such as?mean. - Use a function without attaching its package through
packageName::functionName, such asdplyr::filter().
Installation places a package in an R library, whereas loading makes its exported functions available during the current session. Therefore, a package is generally installed only once but loaded in every new session where it is required.
Describe the important atomic data types and special values available in R. How can an object's type be examined?
Important atomic data types in R include:
- Logical:
TRUEorFALSE - Integer: Whole numbers, commonly written with an
L, such as10L - Double or numeric: Real numbers, such as
10.5 - Character: Text enclosed in quotation marks, such as
"R language" - Complex: Numbers containing an imaginary component, such as
2 + 3i - Raw: Bytes represented in raw form
Important special values include:
NA: A missing or unavailable valueNaN: An undefined numerical result, such as0/0Infand-Inf: Positive and negative infinityNULL: The absence of an object or component
Useful inspection functions are typeof(x), class(x), mode(x), and str(x). Tests such as is.numeric(x) and is.character(x) determine whether an object has a particular form.
Define an R vector. Explain different methods of creating vectors with examples.
A vector is a one-dimensional homogeneous data structure. Every element in an atomic vector must have the same basic type.
Vectors can be created in several ways:
- Combine values with
c():x <- c(2, 4, 6, 8) - Generate an integer sequence:
x <- 1:5 - Use
seq():x <- seq(from = 0, to = 10, by = 2) - Repeat values with
rep():x <- rep(c("A", "B"), times = 2) - Create a logical vector:
x <- c(TRUE, FALSE, TRUE) - Create an initially empty typed vector:
x <- numeric(5)
The length is obtained with length(x). Elements may also be assigned names using names(x) <- c(...), after which they can be accessed by name.
Explain vector indexing and filtering in R using positive, negative, logical, and named indices.
R uses square brackets to select elements from a vector. If x <- c(a = 10, b = 20, c = 30, d = 40), indexing works as follows:
- Positive indexing:
x[c(1, 3)]selects the first and third elements. - Negative indexing:
x[-2]selects all elements except the second. Positive and negative indices must not be mixed in the same index vector. - Logical indexing:
x[x > 20]returns elements whose corresponding condition isTRUE. - Named indexing:
x[c("a", "d")]selects values by their names. - Repeated indexing:
x[c(1, 1, 4)]may select an element more than once.
Logical filtering is particularly important in data analysis because conditions can be combined using operators such as &, |, and !. Missing conditions should be handled carefully because an NA index can produce an NA result.
Explain vectorized arithmetic, recycling, comparison, and missing-value handling in R with examples.
R performs many operations element by element without explicit loops. For example, if x <- c(1, 2, 3) and y <- c(10, 20, 30), then x + y produces c(11, 22, 33) and x^2 produces c(1, 4, 9).
Recycling rule: If vectors have different lengths, the shorter vector is repeated. Thus, c(1, 2, 3, 4) + c(10, 20) gives c(11, 22, 13, 24). R usually warns when the longer length is not a multiple of the shorter length.
Comparison: Expressions such as x > 1 return logical vectors. Use == for equality rather than =.
Missing values:
- Detect them with
is.na(x). - Remove them during calculations using arguments such as
mean(x, na.rm = TRUE). - Avoid testing with
x == NA, because comparison withNAdoes not produce an ordinaryTRUEorFALSEvalue.
Vectorization usually makes R code shorter and more efficient than element-by-element loops.
Describe the representation and manipulation of character strings in R.
Character strings are text values enclosed in single or double quotation marks. For example, course <- "Data Science" creates a character vector of length one.
Common string operations include:
nchar(course)to count characterspaste("Data", "Science")to combine strings with a separatorpaste0("Unit", 12)to combine strings without a separatorsubstr(course, 1, 4)to extract part of a stringtoupper(course)andtolower(course)to change casetrimws(course)to remove surrounding whitespacestrsplit(course, " ")to split a stringgrep("Data", course)to search for a patterngsub("Science", "Analytics", course)to replace matching text
Escape sequences represent special characters, such as \n for a new line and \t for a tab. Since R string functions are generally vectorized, they can process multiple strings in a character vector at once.
What is a matrix in R? Explain matrix creation, naming, indexing, and dimension inspection.
A matrix is a two-dimensional homogeneous data structure. All its elements are stored as the same atomic type.
A matrix can be created using:
m <- matrix(1:6, nrow = 2, ncol = 3, byrow = TRUE)
By default, R fills matrices column by column. Setting byrow = TRUE fills them row by row.
- Assign names using
rownames(m) <- c("R1", "R2")andcolnames(m) <- c("C1", "C2", "C3"). - Access one element with
m[2, 3]. - Access a row with
m[1, ]. - Access a column with
m[, 2]. - Select multiple rows and columns with
m[c(1, 2), c(1, 3)]. - Inspect dimensions with
dim(m),nrow(m), andncol(m).
A vector can also be converted into a matrix by assigning its dim attribute or by using matrix().
Distinguish between element-wise and matrix operations in R. Demonstrate matrix addition, multiplication, transposition, and inversion.
Suppose A and B are matrices of compatible dimensions.
- Addition and subtraction:
A + BandA - Boperate element by element and require equal dimensions. - Element-wise multiplication:
A * Bmultiplies corresponding entries. - Matrix multiplication:
A %*% Bcalculates the matrix product. The number of columns inAmust equal the number of rows inB. - Transpose:
t(A)interchanges the rows and columns. - Inverse:
solve(A)computes whenAis square and nonsingular. - Solving a linear system:
solve(A, b)solves without explicitly calculating the inverse.
If
then A * A squares each entry, whereas A %*% A calculates the standard matrix product. Confusing * with %*% is a common programming error.
Define an R list. Explain how lists are created, accessed, modified, and nested.
A list is a heterogeneous data structure whose components may have different types, lengths, and dimensions. A list can contain vectors, matrices, data frames, functions, and other lists.
Example:
student <- list(name = "Asha", marks = c(80, 85), passed = TRUE)
List operations include:
student[1]returns a sublist containing the first component.student[[1]]extracts the actual first component.student$nameextracts the component namedname.student$grade <- "A"adds a new component.student$passed <- NULLremoves the named component.length(student)returns the number of top-level components.str(student)displays its internal structure.
A nested list contains another list as one of its components. For example, list(person = list(name = "Asha", age = 20)) can be accessed with x$person$name or x[["person"]][["name"]].
Compare vectors, matrices, lists, and data frames in R.
The structures differ in dimensionality and type restrictions:
- Vector: One-dimensional and homogeneous. It stores values of a single atomic type.
- Matrix: Two-dimensional and homogeneous. All cells must share one atomic type.
- List: One-dimensional at the top level and heterogeneous. Each component may contain a different type or structure.
- Data frame: Two-dimensional and heterogeneous across columns. Each column is a vector and must normally have the same number of observations as the other columns.
For example, a numeric vector can store test scores, a matrix can represent purely numeric measurements, a list can store an entire model and its diagnostic objects, and a data frame can represent a table containing names, ages, and scores.
If incompatible types are combined in an atomic vector or matrix, R applies type coercion. Lists and data frames preserve different component or column types, making them more suitable for mixed data.
Explain how a data frame is created and inspected in R. Give an appropriate example.
A data frame is a tabular structure in which rows usually represent observations and columns represent variables. Its columns may have different data types, but they must have compatible lengths.
Example:
students <- data.frame(name = c("Asha", "Ravi"), age = c(20L, 21L), score = c(85.5, 90.0), passed = c(TRUE, TRUE))
Useful inspection functions include:
head(students)andtail(students)to view initial or final rowsstr(students)to inspect structure and column typessummary(students)to obtain descriptive summariesdim(students)to obtain numbers of rows and columnsnrow(students)andncol(students)for individual dimensionsnames(students)orcolnames(students)to view column namesclass(students)to confirm the object's class
A data frame can also be imported from an external file, for example with read.csv("students.csv").
Describe different methods of selecting, filtering, adding, modifying, and deleting rows or columns in an R data frame.
Let df be a data frame.
Selecting data:
df[1, 2]selects one cell.df[1:3, ]selects the first three rows.df[, c("name", "score")]selects named columns.df$scoreordf[["score"]]extracts one column.
Filtering rows:
df[df$score >= 50 & !is.na(df$score), ]selects nonmissing scores of at least 50.subset(df, score >= 50, select = c(name, score))provides a readable alternative.
Changing structure:
df$grade <- c("A", "B")adds a column.df$score <- df$score + 5modifies a column.df$newColumn <- NULLdeletes a column.df <- rbind(df, new_row)appends compatible rows.df <- cbind(df, new_column)appends compatible columns.df <- df[-2, ]removes the second row.
Column lengths, names, and types should be checked after each structural operation.
Explain type coercion in R and discuss how it affects vectors, matrices, lists, and data frames.
Type coercion is the conversion of values from one data type to another. In an atomic structure, R attempts to find a common type capable of representing all elements.
A simplified coercion hierarchy is:
logical → integer → double → complex → character.
For example, c(TRUE, 2, "three") becomes a character vector because character is the common compatible type. Similarly, inserting text into a numeric matrix can convert the entire matrix to character.
Lists do not require a common atomic type, so list(TRUE, 2, "three") preserves the individual types. A data frame also permits different types across columns, although each individual column is normally an atomic vector and is therefore homogeneous.
Explicit conversion functions include as.numeric(), as.character(), as.logical(), as.matrix(), as.list(), and as.data.frame(). After conversion, str(), class(), and typeof() should be used to verify the result. Invalid conversions can produce NA values and warnings.
Describe the general structure of an R program, including comments, statements, assignment, expressions, and functions.
A well-organized R program commonly contains the following sections:
- Documentation and comments: Lines beginning with
#describe the purpose and assumptions of the program. - Setup: Required packages are loaded and configuration values are defined.
- Data input: Data is created or imported.
- Data processing: Objects are cleaned, transformed, and validated.
- Analysis: Statistical or computational operations are performed.
- Output: Results are printed, plotted, or written to files.
R statements are generally separated by new lines or semicolons. Assignment usually uses <-, as in radius <- 5, although = is accepted in many contexts. An expression such as pi * radius^2 is evaluated to produce a value.
Reusable behavior is defined with functions:
area <- function(radius) { pi * radius^2 }
Clear object names, comments explaining intent, modular functions, and minimal dependence on global state improve readability and reproducibility.
Explain conditional statements in R. Compare if, if...else, ifelse(), and switch() with examples.
Conditional statements select which computation to perform.
if: Executes a block when one condition isTRUE:if (score >= 50) { result <- "Pass" }.if...else: Chooses between two blocks:if (score >= 50) { result <- "Pass" } else { result <- "Fail" }.- Nested conditions: Additional categories can be handled using
else if. ifelse(): A vectorized function:ifelse(scores >= 50, "Pass", "Fail"). It tests each element and returns a vector.switch(): Selects an alternative using a character name or numeric position, such asswitch(operation, add = x + y, subtract = x - y).
The condition supplied to if should be a single nonmissing logical value. Use ifelse() for element-wise decisions over vectors, while if and if...else are more suitable for controlling program flow.
Compare the loop structures for, while, and repeat in R. Explain the roles of break and next.
R provides three principal loop structures:
forloop: Iterates over a known sequence. Example:for (x in 1:5) { print(x^2) }.whileloop: Repeats while a condition remainsTRUE. Example:while (x < 5) { x <- x + 1 }.repeatloop: Repeats indefinitely until explicitly terminated. Example:repeat { x <- x + 1; if (x >= 5) break }.
Loop-control statements are:
break: Immediately exits the innermost loop.next: Skips the rest of the current iteration and begins the next one.
A for loop is appropriate when the iteration sequence is known. A while loop is useful when repetition depends on a condition, while repeat is useful when termination is checked inside the body. Conditions must eventually change; otherwise, while and repeat can create infinite loops. Vectorized operations or apply-family functions may be preferable for many data transformations.
Design and explain an R function that calculates summary statistics for a numeric vector while handling missing values.
One possible function is:
describe_values <- function(x, remove_na = TRUE) {
if (!is.numeric(x)) stop("x must be numeric")
if (!remove_na && anyNA(x)) return(list(mean = NA_real_, median = NA_real_, sd = NA_real_, n = length(x)))
clean_x <- if (remove_na) x[!is.na(x)] else x
if (length(clean_x) == 0) stop("no nonmissing values are available")
list(mean = mean(clean_x), median = median(clean_x), sd = sd(clean_x), n = length(clean_x))
}
Explanation:
function(x, remove_na = TRUE)declares one required argument and one default argument.is.numeric()validates the input, andstop()reports invalid usage.anyNA()efficiently checks for missing values.- Logical indexing removes
NAvalues when requested. mean(),median(), andsd()compute the summaries.- A named list returns several values of potentially different meanings in one object.
The function demonstrates arguments, defaults, validation, conditionals, local variables, missing-value handling, and structured return values.
Define R and explain its major features and applications in data science.
R is an open-source programming language and software environment designed for statistical computing, data analysis, and graphical visualization.
Major features:
- It is free, open-source, and available on Windows, Linux, and macOS.
- It provides extensive support for statistical tests, machine learning, and data visualization.
- Thousands of reusable packages are available through the Comprehensive R Archive Network (CRAN).
- It supports vectorized operations, reducing the need for explicit loops.
- It can import data from text files, spreadsheets, databases, and web-based sources.
- It produces publication-quality graphics through base R and packages such as ggplot2.
Applications in data science:
- Data cleaning and transformation
- Exploratory data analysis
- Statistical modeling
- Machine learning
- Data visualization
- Reproducible research and report generation
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →