0% found this document useful (0 votes)
2 views19 pages

R Programming Exam Guide

The document provides a comprehensive overview of the R programming language, detailing its advantages, special values, data structures, looping statements, functions, and graphical capabilities. It covers essential concepts such as vectors, matrices, lists, arrays, and various data types, along with examples of descriptive statistics and input/output operations. Additionally, it includes sample R programs for calculating statistical measures and generating different types of graphs.

Uploaded by

stevelouis348
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views19 pages

R Programming Exam Guide

The document provides a comprehensive overview of the R programming language, detailing its advantages, special values, data structures, looping statements, functions, and graphical capabilities. It covers essential concepts such as vectors, matrices, lists, arrays, and various data types, along with examples of descriptive statistics and input/output operations. Additionally, it includes sample R programs for calculating statistical measures and generating different types of graphs.

Uploaded by

stevelouis348
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

R PROGRAMMING LANGUAGE

Complete Master Answer Key (7-10 Marks Exams Questions)

Q1. Explain the advantages of R language over other programming


languages.

Introduction: R is an open-source programming language and environment specifically built for


statistical computing, data analytics, and scientific research. It was developed by Ross Ihaka and
Robert Gentleman at the University of Auckland.

Key Advantages of R:

• Open Source and Completely Free: R is released under the GNU General Public License.
Anyone can download it instantly, inspect or modify the underlying source code, and distribute it
without paying any commercial licensing or subscription fees.
• Outstanding Data Visualization: R has unmatched advanced graphics capabilities. Using built-
in graphical engines or cutting-edge external packages like ggplot2, users can generate
publication-quality charts, graphs, maps, and plots with deep customization layers.
• Massive Ecosystem of Packages: R features CRAN (Comprehensive R Archive Network), a
centralized repository hosting over 18,000+ specialized packages. This allows developers to
implement complex machine learning algorithms or data structures with a single command.
• Built Exclusively for Statistics: Unlike general-purpose software or languages like Python and
Java, R was structurally engineered from scratch for quantitative data analysis. It handles matrix
algebra, statistical modeling, and data summaries naturally.
• Cross-Platform Compatibility: R is completely platform-independent. Code written on a
Windows operating system compiles and runs smoothly on macOS, Linux, or UNIX distributions
without requiring modification.
• Strong Global Community: R has an active community of elite data scientists, statisticians, and
academic research professionals who continuously update code libraries and provide support to
beginners online.

Q2. Explain different special values in R with examples.

R features distinct data constants explicitly designed to represent missing values, mathematical
boundaries, or empty structures during computations.

R Programming - End Semester Examination Question Bank Page 1 of 19


1. NA (Not Available)
Used to represent missing, omitted, or unknown values inside a data object. It preserves the
missing component's structural position without breaking operations.

# A vector where the third student's marks are missing


marks <- c(85, 92, NA, 78)
print([Link](marks)) # Returns: FALSE FALSE TRUE FALSE

2. NaN (Not a Number)


Represents mathematically undefined or impossible results, such as division by zero or square
roots of negative numbers when dealing with real components.

invalid_val <- 0 / 0
print(invalid_val) # Output: NaN
print([Link](invalid_val)) # Returns: TRUE

3. Inf and -Inf (Infinity)


Represents values that are infinitely large or small, completely exceeding R's standard numeric
capacity. This occurs when a positive or negative number is divided by zero.

pos_inf <- 5 / 0 # Output: Inf


neg_inf <- -5 / 0 # Output: -Inf

4. NULL (Empty Object)


Represents a completely empty, null, or non-existent data structure. Unlike NA, which flags a
missing piece inside a slot, NULL means the object contains absolutely no values or structure.

empty_var <- NULL


print(empty_var) # Output: NULL

Q3. Explain vectors and matrices in R with suitable examples.

Vectors
A vector is the most fundamental, one-dimensional data structure in R. It holds components
belonging strictly to the same data type (homogeneous). We construct vectors using the combine
function c().

R Programming - End Semester Examination Question Bank Page 2 of 19


# Creating a numeric vector
num_vec <- c(10, 20, 30, 40)

# Creating a character vector


fruit_vec <- c("Apple", "Banana", "Mango")

Matrices
A matrix is a two-dimensional rectangular data layout organized cleanly into rows and columns.
Like vectors, all items inside a matrix must share the identical data type. We construct matrices
using the matrix() function.

Syntax: matrix(data, nrow, ncol, byrow)

# Creating a 2x3 matrix filled column-by-column


my_matrix <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3)
print(my_matrix)

# Creating a matrix filled row-by-row


row_matrix <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3, byrow = TRUE)
print(row_matrix)

Q4. Discuss different looping statements in R language.

Loops are control blocks used to repeatedly run a specific block of code as long as a particular
condition is met or an iterable sequence is active.

1. The for Loop


Used when you know exactly how many times the block of code needs to repeat beforehand.

# Prints numbers from 1 to 5


for (i in 1:5) {
print(i)
}

2. The while Loop


Repeats execution as long as a specified control condition remains TRUE. The condition is evaluated
*before* the loop body runs.

R Programming - End Semester Examination Question Bank Page 3 of 19


count <- 1
while (count <= 3) {
print(count)
count <- count + 1 # Dynamic increment
}

3. The repeat Loop


An infinite loop structure that executes code repeatedly without checking an initial condition. It
requires an explicit conditional break statement inside to terminate safely.

x <- 1
repeat {
print(x)
x <- x + 1
if (x > 3) {
break # Halts the loop
}
}

Q5. Explain built-in and user-defined functions in R with examples.

A function is a structural block of reusable code written to perform a single, isolated computational
task.

1. Built-in Functions
These are pre-compiled functions readily available in the base environment of R without requiring
any custom coding from the user.

print(sqrt(25)) # Output: 5 (Calculates square root)


print(max(12, 84, 3)) # Output: 84 (Finds the maximum value)
print(toupper("r")) # Output: "R" (Converts string to uppercase)

2. User-Defined Functions
Custom operations created by the programmer to perform unique repetitive workflows using the
function keyword.

Syntax:

R Programming - End Semester Examination Question Bank Page 4 of 19


func_name <- function(param1, param2) {
# Code block execution
return(result)
}

Example Program:

# Function to calculate the cube of an integer


calculate_cube <- function(num) {
cube_val <- num * num * num
return(cube_val)
}

# Invoking the function


output <- calculate_cube(4)
print(output) # Output: 64

Q6. Write short notes on: (a) Lists in R, (b) Arrays in R.

(a) Lists in R
A list is a one-dimensional, heterogeneous data object. Unlike vectors, a list can seamlessly store
a mix of completely different data types inside its elements, such as numbers, string values, multi-
dimensional matrices, vectors, or nested lists.

# Creating a list with mixed data types


student_record <- list(name = "Karan", age = 22, scores = c(90, 85, 88), pass
= TRUE)
print(student_record)

# Accessing named attributes via the dollar ($) syntax


print(student_record$name) # Output: "Karan"

(b) Arrays in R
An array is a multi-dimensional ($n$-dimensional) data structure. While a matrix is strictly limited
to two dimensions (rows & columns), arrays expand to handle 3D, 4D, or higher data layers (like
grouping multiple individual matrices into a multi-layered block). It can only hold homogeneous
data.

R Programming - End Semester Examination Question Bank Page 5 of 19


# Creating a 3D array containing two distinct 2x3 matrices
# dim parameter format: c(rows, columns, matrices)
my_array <- array(c(1:12), dim = c(2, 3, 2))
print(my_array)

Q7. Explain string manipulation functions in R with examples.

Strings represent characters or text segments enclosed inside single or double quotes. R provides
robust built-in functions for editing and manipulating text elements:

1. paste()
Combines or links multiple independent string tokens into a single cohesive string sequence,
separated by a space by default.

part1 <- "Data"


part2 <- "Analysis"
print(paste(part1, part2)) # Output: "Data Analysis"

2. nchar()
Counts the exact total number of characters, letters, punctuation, and empty spacing elements
contained inside a targeted string.

print(nchar("R Core")) # Output: 6

3. toupper() and tolower()


Modifies the absolute font casing of text sequences to either full uppercase or lowercase formats.

print(toupper("exam")) # Output: "EXAM"


print(tolower("CODE")) # Output: "code"

4. substr()
Extracts or substitutes a small, localized sub-segment of text from a parent string based on explicit
start and stop element indices.

# Extract characters from position 3 to 6


print(substr("Development", 3, 6)) # Output: "velo"

R Programming - End Semester Examination Question Bank Page 6 of 19


5. sub()
Finds and replaces the very first occurrence of a specific word pattern matching an input query
inside a target text.

phrase <- "Hot day, hot summer"


print(sub("hot", "cool", phrase)) # Output: "Hot day, cool summer"

Q8. Discuss different types of graphs available in R.

R features deep core functions to graphically plot data, helping users analyze distributions, track
outliers, and map dependencies visually.

• Pie Chart: A circular chart partitioned into proportional angular wedges. It visualizes the
component composition or relative percentages making up a whole entity. Created using pie().
• Bar Chart: Uses vertical or horizontal rectangular blocks to display discrete metric scales across
distinct categorical groups. Created using barplot().
• Histogram: A density bar graph mapped over continuous numerical values. It buckets numbers
into balanced value ranges called bins to show frequency distribution. Created using hist().
• Scatter Plot: Plots data coordinate observations as distinct points across horizontal ($X$) and
vertical ($Y$) axes. It helps establish correlations between two numeric variables. Created using
plot().

• Box Plot: Summarizes numeric data profiles via a five-number summary: absolute minimum,
lower quartile ($Q1$), median, upper quartile ($Q3$), and absolute maximum. Created using
boxplot().

Q9. Explain R data types in detail with examples.

R contains 5 fundamental, atomic data types. You can inspect the data type class of any variable at
run time using the class() function.

R Programming - End Semester Examination Question Bank Page 7 of 19


Data Standard Assignment Code
Structural Definition
Type Example

Default type for real, fractional, or decimal


Numeric val1 <- 45.82
numbers.

Strict whole numbers. Declared by appending an 'L'


Integer val2 <- 14L
suffix.

Text strings or individual characters wrapped in


Character val3 <- "Data Science"
quotes.

Boolean data properties representing TRUE or


Logical val4 <- FALSE
FALSE.

Values containing matching real and imaginary


Complex val5 <- 2 + 5i
parts ($a + bi$).

Q10. Write an R program to calculate mean, median and standard deviation


of a dataset and explain the output.

R Code Script

# 1. Defining a raw dataset containing student test scores


test_scores <- c(65, 70, 75, 80, 85, 90, 95)

# 2. Executing basic mathematical descriptive calculations


res_mean <- mean(test_scores)
res_median <- median(test_scores)
res_sd <- sd(test_scores)

# 3. Printing the computed summaries to console


cat("Calculated Mean Score:", res_mean, "
")
cat("Calculated Median Score:", res_median, "
")
cat("Calculated Standard Deviation:", res_sd, "
")

R Programming - End Semester Examination Question Bank Page 8 of 19


Explanation of Output
• Mean (80): This represents the traditional arithmetic center point of the test scores. It is
calculated by adding all individual test scores together and dividing the sum by the total count of
observations ($560 / 7 = 80$).
• Median (80): Represents the exact midpoint value when data is sorted sequentially. Since there
are 7 scores, the 4th item ($80$) divides the dataset evenly into matching halves.
• Standard Deviation (10.80): Measures the dispersion or spread of scores relative to the mean. A
standard deviation of $10.80$ shows that most students' scores deviate from the average center
by roughly $\pm 10.80$ marks.

Q11. Explain pie chart, histogram and bar chart with suitable R programs.

1. Pie Chart Program

# Plotting proportionate slices of monthly personal expenses


expense_values <- c(45, 35, 20)
expense_labels <- c("Rent", "Food", "Utilities")
pie(expense_values, labels = expense_labels, main = "Expense Breakdown")

2. Bar Chart Program

# Comparing distinct categorical profits across quarters


quarter_profits <- c(150, 280, 200, 310)
quarter_names <- c("Q1", "Q2", "Q3", "Q4")
barplot(quarter_profits, [Link] = quarter_names, col = "skyblue", main =
"Quarterly Gains")

3. Histogram Program

# Analyzing how weight metrics group up into uniform value buckets


people_weights <- c(55, 58, 62, 63, 64, 68, 71, 75, 82, 85)
hist(people_weights, col = "lightgreen", main = "Weight Frequency Range")

Q12. Discuss descriptive statistics in R language with examples.

Descriptive statistics organize, summarize, and outline the key behavioral attributes of a dataset
without drawing experimental inferences. R provides rapid built-in operators to compute these
indicators:

R Programming - End Semester Examination Question Bank Page 9 of 19


1. Measures of Central Tendency
Identifies the central clustering point of numeric observations.

• Mean: The mathematical average value. Calculated via mean(x).


• Median: The exact central item of an ordered sequence. Calculated via median(x).

2. Measures of Dispersion
Maps how spread out or scattered the numbers are around the average value.

• Range: Displays minimum and maximum value limits. Calculated via range(x).
• Standard Deviation: The typical distance of data points from the mean. Calculated via sd(x).
• Variance: The squared deviation value. Calculated via var(x).

The summary() Function Example


Instead of running separate calculations, R includes a master utility called summary() that instantly
delivers a comprehensive evaluation including the minimum, 1st quartile, median, mean, 3rd
quartile, and maximum values of a vector.

sample_data <- c(12, 18, 22, 29, 35, 42, 58)


summary(sample_data)

Q13. Explain the features of R language.

R possesses unique structural design attributes that make it popular for enterprise-grade analytics
workflows:

• Vectorized Calculations: R eliminates the absolute need for explicit loops to run simple
processing arrays. Applying an operation to an entire vector instantly modifies every cell natively.
• Robust Data Structure Types: R includes powerful native structures like Data Frames, which
seamlessly handle Excel-style datasets containing diverse text, logic, and numeric rows.
• Seamless Language Integration: For deep optimization tasks, R can link directly with low-level
procedures written in C, C++, and Fortran to execute computations at faster machine speeds.
• Extensive Dynamic Graphics Engines: Beyond standard base plots, R features modular styling
platforms like Lattice and grammar-driven systems like ggplot2.
• Active Global Academic Support: R serves as the primary software platform for modern
statistical research globally, meaning cutting-edge algorithms are released in R before any other
language.

R Programming - End Semester Examination Question Bank Page 10 of 19


Q14. Explain input and output operations in R with examples.

Input Operations
Input workflows allow an active R program to ingest raw data characters from terminal operators or
external computer files.

• readline(): Pauses script execution and reads a single typed text response string from a user via
the runtime console.

user_name <- readline(prompt = "Enter your student ID: ")

• [Link](): Automatically parses external spreadsheet files (.csv) into memory and converts
them into an accessible data frame.

loaded_data <- [Link]("exam_records.csv")

Output Operations
Output workflows print processed results to the screen or save them onto a hard drive.

• print(): Simple command to output a single variable or explicit data object onto the terminal.

print("Processing Complete")

• cat(): Concatenates and prints multiple elements, combining variables and custom strings
together cleanly without system quotes or brackets.

score_val <- 95
cat("Final Score attained:", score_val, "marks.
")

• [Link](): Exports in-memory data frames or matrix objects out of R, saving them as structural
spreadsheet files.

[Link](loaded_data, "cleaned_report.csv")

Q15. Explain different operators in R language with examples.

Operators are symbolic characters that instruct the compiler to perform logical or mathematical
manipulations on variables.

R Programming - End Semester Examination Question Bank Page 11 of 19


1. Arithmetic Operators
Used to perform foundational calculations.

• + (Addition), - (Subtraction), * (Multiplication), / (Division)


• %% (Modulus - outputs the remainder): 8 %% 3 yields 2.
• ^ (Exponent Power): 3 ^ 2 yields 9.

2. Relational Operators
Compares data properties. They always return a logical TRUE or FALSE outcome.

• < (Less than), > (Greater than), == (Equal to), != (Not equal to)

3. Logical Operators
Combines multiple conditional states together.

• & (Element-wise AND): Returns TRUE if both compared items evaluate to true.
• | (Element-wise OR): Returns TRUE if at least one side evaluates to true.
• ! (Logical NOT): Inverts truth values (converts TRUE into FALSE).

4. Assignment Operators
Binds value metrics to variables. The left-arrow symbol (<-) is the preferred assignment operator in
R.

Q16. Discuss decision-making statements in R with examples.

Decision statements branch program logic depending on whether a tested conditional expression
resolves to true or false.

1. The if Statement
Runs a specific internal block of code if the tested target condition evaluates to TRUE.

grade_point <- 65
if (grade_point >= 40) {
print("Result status: Pass")
}

2. The if-else Statement


Provides an alternate fallback path of execution if the primary conditional query tests as FALSE.

R Programming - End Semester Examination Question Bank Page 12 of 19


voter_age <- 15
if (voter_age >= 18) {
print("Eligible to Vote")
} else {
print("Not Eligible to Vote")
}

3. The switch() Function


Acts as a multi-way branch selector that evaluates an index expression and executes the
corresponding named case option.

index_key <- "3"


chosen_month <- switch(index_key, "1"="Jan", "2"="Feb", "3"="Mar")
print(chosen_month) # Output: "Mar"

Q17. Explain vectors and lists in R with examples.

The primary architectural difference between vectors and lists in R lies in data homogeneity versus
heterogeneity.

Vectors (Homogeneous)
Vectors are linear data structures constrained to store components of the exact same data type. If
different data types are combined, R forces automatic internal conversion to the most flexible type
(type coercion).

# Creating a clean numeric vector


v_num <- c(5, 10, 15)

# Mixing data types forces all elements into character text strings
v_mix <- c(7, "Apple", TRUE)
print(v_mix) # Output: "7" "Apple" "TRUE"

Lists (Heterogeneous)
Lists are multi-type container structures. They store data components belonging to completely
different classifications (characters, matrices, logical properties, functions) simultaneously without
altering their original type properties.

R Programming - End Semester Examination Question Bank Page 13 of 19


# Creating a list that preserves its native internal structures
my_list_obj <- list(45L, "Data Science", FALSE)
print(my_list_obj)

Q18. Explain matrices and arrays in R language.

Both data structures handle collections of uniform, homogeneous data fields across explicit
directional boundaries.

Matrix (2-Dimensional)
A matrix is a two-dimensional grid layout constrained strictly to vertical columns and horizontal rows.
It is commonly used for standard linear algebra calculations.

# Instantiating a 3-row, 2-column matrix


matrix_grid <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 3, ncol = 2)
print(matrix_grid)

Array (Multi-Dimensional)
An array is an n-dimensional data object that extends beyond two dimensions. For example, a 3D
array can be conceptualized as stacking multiple independent matrices on top of each other as
sequential layers.

# Building a 3-dimensional block of dimensions (2 rows, 3 columns, 2 layers)


array_block <- array(c(1:12), dim = c(2, 3, 2))
print(array_block)

Q19. Explain bitwise operators in R with suitable examples.

Bitwise operators perform logical evaluations directly on the raw binary digits (0s and 1s)
representing integers. R executes these processes using built-in system tools:

1. bitwAnd(a, b)
Compares matching binary bits; outputs a 1 only if both compared data bits contain a 1 value.

# 5 is represented as 101 in binary


# 3 is represented as 011 in binary
print(bitwAnd(5, 3)) # Output: 1 (Binary representation: 001)

R Programming - End Semester Examination Question Bank Page 14 of 19


2. bitwOr(a, b)
Compares binary bits; outputs a 1 if at least one of the matching bits contains a 1 value.

print(bitwOr(5, 3)) # Output: 7 (Binary representation: 111)

3. bitwXor(a, b)
Performs an exclusive OR evaluation. Outputs a 1 if the compared bits are different, and a 0 if they
are identical.

print(bitwXor(5, 3)) # Output: 6 (Binary representation: 110)

4. bitwNot(a)
Inverts every bit of the integer, transforming all 0s into 1s and all 1s into 0s.

Q20. Explain different data visualization techniques in R.

Data visualization techniques translate numeric metrics into clear charts to reveal trends,
distributions, and patterns. R organizes visualization workflows through three graphics architectures:

• Base Graphics System: The native, core visualization engine built into R. It is highly efficient for
running quick, single-line exploratory commands like plot(), hist(), or boxplot() without
loading external dependencies.
• The ggplot2 Package System: An advanced package based on the Grammar of Graphics. It
allows users to build highly customized plots by programmatically stacking individual data layers,
aesthetics (mapping columns to axes/colors), and geometries (points, bars, lines) on top of each
other.
• Lattice System: A specialized graphics package designed to generate multi-panel grid displays
(trellis plots). It is useful for looking at sub-group relationships across multiple categorical
variables simultaneously.

Q21. Explain loops and loop control statements in R with examples.

While standard loops automate code repetitions, loop control statements allow you to alter or skip
execution steps based on real-time conditional checks during execution loops.

Loop Control Statement Types:


• next: Instantly skips the remaining lines of code inside the loop for the current iteration, jumping
directly to the evaluation of the next cycle (similar to 'continue' in other languages).

R Programming - End Semester Examination Question Bank Page 15 of 19


• break: Instantly terminates the entire loop execution and forces program control to jump
completely outside the loop container blocks.

Comprehensive Code Example:

# Implementing both loop control statements inside a sequential loop


for (val in 1:6) {
if (val == 3) {
next # Skips printing the number 3 and increments immediately
}
if (val == 5) {
break # Halts the entire loop loop when value hits 5
}
cat("Active Value:", val, "
")
}
# Expected Printed Output: 1, 2, 4

R Programming - End Semester Examination Question Bank Page 16 of 19


Q22. Write an R program to create and manipulate strings using different
string functions.

R Code Script

# 1. Instantiating text string variables


word_alpha <- "statistical"
word_beta <- "computing"

# 2. Merging distinct strings using paste()


merged_phrase <- paste(word_alpha, word_beta)
cat("Merged Result:", merged_phrase, "
")

# 3. Computing character length using nchar()


length_count <- nchar(merged_phrase)
cat("Character Count:", length_count, "
")

# 4. Modifying text case using toupper()


upper_result <- toupper(merged_phrase)
cat("Uppercase Convert:", upper_result, "
")

# 5. Extracting text slices using substr()


sub_slice <- substr(merged_phrase, 1, 11)
cat("Extracted Slice:", sub_slice, "
")

Q23. Explain descriptive statistics in R with suitable examples and


programs.

Descriptive statistics provide a clear summary of a dataset's distribution, central point, and overall
variability before performing advanced modeling workflows.

R Programming - End Semester Examination Question Bank Page 17 of 19


Analytical Code Script

# Dataset modeling product delivery turnaround times in days


delivery_records <- c(3, 4, 4, 5, 5, 6, 22) # 22 represents a distinct
outlier

# Extracting core descriptive metrics


out_mean <- mean(delivery_records)
out_median <- median(delivery_records)
out_sd <- sd(delivery_records)

cat("Mean Time:", out_mean, "


")
cat("Median Time:", out_median, "
")
cat("Standard Deviation Spread:", out_sd, "
")

Analytical Interpretation
Analyzing the program output shows that the median delivery time is quite low ($5$ days). However,
the calculated mean ($7$ days) is pulled artificially high due to the presence of a single outlier value
($22$ days). The standard deviation indicates how widely dispersed the turnaround values are
relative to that central mean.

Q24. Write short notes on the following with examples: (a) Pie Chart, (b)
Histogram, (c) Scatterplot.

(a) Pie Chart


A circular graph divided into sectors or slices, where the area of each slice represents its proportion
of the whole dataset. It is best used for comparing categorical variables to show their relative shares.
For example, displaying a company's market share distribution among competitors. Created using
pie().

(b) Histogram
A bar-style plot that visualizes the distribution of continuous numerical data. It groups continuous
data into consecutive, equal intervals called bins, and the height of each bar displays the frequency
of observations within that range. For example, tracking the height distribution of a population.
Created using hist().

R Programming - End Semester Examination Question Bank Page 18 of 19


(c) Scatterplot
A two-dimensional chart that uses coordinate dots to display the values of two numerical variables
across an $X$ and $Y$ axis grid. It is primarily used to analyze relationships or find correlations
between variables. For example, evaluating whether student study hours correlate with higher final
exam scores. Created using plot().

R Programming - End Semester Examination Question Bank Page 19 of 19

You might also like