0% found this document useful (0 votes)
40 views17 pages

Question Paper 1 Answers (R) by Siddu

The document is a comprehensive question paper covering various topics in R programming, including data types, loops, matrix operations, data frames, statistical measures, and data visualization techniques. It includes multiple-choice questions, programming tasks, and explanations of functions and concepts in R. Each module focuses on different aspects of R programming, providing practical coding examples and theoretical explanations.

Uploaded by

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

Question Paper 1 Answers (R) by Siddu

The document is a comprehensive question paper covering various topics in R programming, including data types, loops, matrix operations, data frames, statistical measures, and data visualization techniques. It includes multiple-choice questions, programming tasks, and explanations of functions and concepts in R. Each module focuses on different aspects of R programming, providing practical coding examples and theoretical explanations.

Uploaded by

Nikhil Kannale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Question Paper 1

Module-1
Q1.

a. Determine the output of the following R statements:

i) C(1, 2, 3, 4, 5) + C(6, 7, 8, 9, 10)

ii) 1:4 - 2:3

iii) identical(2^3, 2**3)

iv) 5:9 %% 2

v) C(2, 4 - 2, 1 - 1) - 0

b. Explain the basic data types of R with examples.

c. Develop an R program to find the factorial of a given number using 5 recursive function
calls.

OR

Q2.

a. Explain repeat, while, and for loops with R programming examples

b. Develop R code to calculate the following financial metrics using the data below:

Monthly Revenue: [150, 60, 70, 80, 90, 100, 110, 120, 130, 140, 155, 165]

Monthly Expenses: [30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85]

i) Profit for each month.

ii) Profit after tax for each month (tax rate = 30%).

iii) Profit margin for each month.

iv) Identify "Good" months (profit after tax > mean profit) and "Bad" months (profit after tax
< mean profit).
v) Identify the "Best" and "Worst" months where profit after tax is maximum and minimum,
respectively.

Module-2
Q3.

a. Develop an R program to create two 3x3 matrices A and B and perform the following
operations:

i) Transpose of the matrices.

ii) Addition.

iii) Subtraction.

iv) Multiplication.

v) Access the first row of matrix A.

b. Describe the following with R programming examples:

i) Creation of lists.

ii) Assigning names to elements of a list.

iii) Accessing elements of a list using index and names.

iv) Conversion of a vector to a list.

v) Combining two lists.

OR

Q4.

a. Determine the output of the following R statements:

i) paste("Cupin", "Red", "Apple")

ii) substring("The cat is on the wall", 3, 10)

iii) strsplit("I like Banana, Orange, and Pineapple")


iv) basename("C:/Program Files/test.R")

v) gl(5, 3, labels = c("one", "two", "three", "four", "five"))

b. Develop an R program to create a data frame with the following details:

Item Code | Item Category | Item Price

1001 | Electronics | 700

1002 | Desktop Supplies | 300

1003 | Office Supplies | 350

1004 | USB | 400

1005 | CD Drive | 800

Perform the following operations:

i) Subset the data frame to display items with a price ≥ 350.

ii) Subset the data frame to display items in "Office Supplies" or "Desktop Supplies" category.

iii) Create another data frame called item_details with fields Item Code, ItemQtyOnHand, and
ItemReorderLevel. Merge the two data frames.

Module-3

Q5.

a. Describe the following data frame manipulation functions with examples:

i) with()

ii) within()

iii) order()

b. Design a data frame in R for storing 10 employee details and create a CSV file named
input_CSV containing the details such as ID, Name, Salary, Start Date, and Department.
Perform the following:
i) Find the total number of rows and columns.

ii) Find the maximum salary.

iii) Retrieve details of the employee with the maximum salary.

iv) Retrieve employees in the IT department with a salary > 20,000.

v) Retrieve all employees in the IT department.

OR

Q6.

a. Illustrate the concept of the following grouping functions with examples:

i) apply()

ii) lapply()

iii) mapply()

iv) rapply()

v) tapply()

(10 Marks)

b. Explain the functions used for importing and exporting unstructured files with examples.

Module - 4
Q7.

a. Write the basic syntax for creating a pie chart, explain each parameter of the function, and
write an R program to create a pie chart for the given flower data:

[Rose: 25, Lotus: 35, Lily: 10, Sunflower: 5, Jasmine: 15]. Create a crested pie chart.

(10 Marks)
b. Explain different ways of creating scatter plots in R.

(10 Marks)

OR

Q8.

a. Demonstrate vertical and horizontal bar plots using graphics with examples.

(10 Marks)

b. Describe the following with examples:

i) hist()

ii) plot()

iii) boxplot()

iv) bwplot()

v) ggplot()

Module - 5
Q9.

a. Define the basic statistical measures: Mean, Median, Mode, Standard Deviation, and
Variance. Develop R code to create a vector x = [45, 56, 78, 12, 3, -91, 45, 15, 1, 24] and
compute these measures.

(10 Marks)

b. What is normal distribution? Explain different types of normal distribution functions built
into R.

(10 Marks)

OR
Q10.

a. Use the mtcars dataset in R to:

i) Find the correlation between hp (horsepower) and mpg (mileage per gallon) and plot a
graph of hp vs. mpg.

ii) Find the correlation between hp and disp (displacement) and plot a graph of hp vs. disp.

iii) Analyze the correlation between the various columns in the dataset.

b. Explain linear regression analysis with examples.

Module-1

Q1:

a. Determine the output of the following R statements:

i) C(1, 2, 3, 4, 5) + C(6, 7, 8, 9, 10)


Output: [1] 7 9 11 13 15

ii) 1:4 - 2:3


Explanation: This involves vectors of unequal lengths; the shorter vector is recycled.
Output: [1] -1 0 1 2

iii) identical(2^3, 2**3)


Explanation: Both ^ and ** represent exponentiation in R.
Output: [1] TRUE

iv) 5:9 %% 2
Explanation: The modulo operator (%%) returns the remainder of division.
Output: [1] 1 0 1 0 1

v) C(2, 4 - 2, 1 - 1) - 0
Explanation: Subtracting 0 does not change the vector.
Output: [1] 2 2 0
b. Explain the basic data types in R with examples:

R has five basic data types:

1. Numeric:
Example: x <- 10.5

class(x) # Output: "numeric"

2. Integer:
Example: y <- as.integer(3)

class(y) # Output: "integer"

3. Complex:
Example: z <- 3 + 4i

class(z) # Output: "complex"

4. Logical:
Example: a <- TRUE

class(a) # Output: "logical"

5. Character:
Example: s <- "Hello"

class(s) # Output: "character"

c. Develop an R program to find the factorial of a number using recursion:


Code:

factorial_recursive <- function(n) {

if (n <= 1) return(1)

return(n * factorial_recursive(n - 1))

factorial_recursive(5) # Output: 120

OR Q2:
a. Explain repeat, while, and for loops in R with examples:

1. Repeat Loop:
Example: a <- 1

repeat {

print(a)

a <- a + 1

if (a > 5) break

2. While Loop:
Example: a <- 1

while (a <= 5) {

print(a)

a <- a + 1

3. For Loop:
Example: for (i in 1:5) {

print(i)

b. Financial metrics calculation with provided data:

1. Monthly Profit: profit <- revenue - expenses

2. Profit After Tax (30%): profit_after_tax <- profit * 0.7

3. Profit Margin: profit_margin <- profit_after_tax / revenue * 100

4. Good and Bad Months: mean_profit <- mean(profit_after_tax)

good_months <- profit_after_tax > mean_profit

bad_months <- profit_after_tax < mean_profit

5. Best and Worst Months: best_month <- which.max(profit_after_tax)


worst_month <- which.min(profit_after_tax)

Module-2

Q3:

a. Operations on 3x3 matrices:

1. Create Matrices: A <- matrix(1:9, nrow = 3, byrow = TRUE)

B <- matrix(9:1, nrow = 3, byrow = TRUE)

2. Transpose of Matrices: transpose_A <- t(A)

transpose_B <- t(B)

3. Addition, Subtraction, Multiplication: addition <- A + B

subtraction <- A - B

multiplication <- A %*% B

4. Access First Row of A: first_row_A <- A[1, ]

b. Lists in R:

1. Create a List: my_list <- list(name = "John", age = 25, scores = c(90, 85, 88))

2. Assign Names to Elements: names(my_list) <- c("Name", "Age", "Scores")

3. Access Elements: my_list$Name # Access by name

my_list[[1]] # Access by index

4. Convert Vector to List: vec <- c(1, 2, 3)

vec_list <- as.list(vec)

5. Combine Two Lists: list1 <- list(a = 1, b = 2)

list2 <- list(c = 3, d = 4)

combined_list <- c(list1, list2)


OR Q4:

a. Outputs of R Statements:

1. paste("Cupin", "Red", "Apple"):


Output: [1] "Cupin Red Apple"

2. substring("The cat is on the wall", 3, 10):


Output: [1] "e cat i"

3. strsplit("I like Banana, Orange, and Pineapple", ","):


Output: [[1]] [1] "I like Banana" " Orange" " and Pineapple"

4. basename("C:/Program Files/test.R"):
Output: [1] "test.R"

5. gl(5, 3, labels = c("one", "two", "three", "four", "five")):


Output: A factor of length 15 with levels: one, two, three, four, five.

b. Data Frame Operations:

1. Create Data Frame: items <- data.frame(

Item_Code = c(1001, 1002, 1003, 1004, 1005),

Item_Category = c("Electronics", "Desktop Supplies", "Office Supplies", "USB", "CD Drive"),

Item_Price = c(700, 300, 350, 400, 800)

2. Subset Price ≥ 350: subset_price <- subset(items, Item_Price >= 350)

3. Subset by Category:

CopyEdit

subset_category <- subset(items, Item_Category %in% c("Office Supplies", "Desktop Supplies"))

4. Merge with Another Data Frame: item_details <- data.frame(

Item_Code = c(1001, 1002, 1003, 1004, 1005),

ItemQtyOnHand = c(10, 15, 20, 25, 30),

ItemReorderLevel = c(5, 5, 10, 10, 15)


)

merged_data <- merge(items, item_details, by = "Item_Code")

Module-3

Q5:

a. Describe the following data frame manipulation functions with examples:

1. with():
Executes code within a data frame without explicitly referencing it.
Example: df <- data.frame(x = 1:3, y = c(4, 5, 6))

with(df, x + y) # Output: [1] 5 7 9

2. within():
Modifies a data frame by directly editing its columns.
Example:

df <- data.frame(x = 1:3, y = c(4, 5, 6))

df <- within(df, {z <- x * y})

print(df)

Output:

xy z

114 4

2 2 5 10

3 3 6 18

3. order():
Orders a data frame by specified columns.
Example:

df <- data.frame(x = c(3, 1, 2), y = c(6, 4, 5))

df[order(df$x), ]

Output:
xy

214

325

136

b. Employee data frame operations and CSV file creation:

1. Create Data Frame:

emp <- data.frame(

ID = 1:10,

Name = paste("Emp", 1:10),

Salary = c(20000, 30000, 25000, 40000, 35000, 22000, 27000, 32000, 28000, 31000),

Start_Date = as.Date("2023-01-01") + 0:9,

Department = c("IT", "HR", "Finance", "IT", "Finance", "HR", "IT", "Finance", "HR", "IT")

write.csv(emp, "input_CSV.csv", row.names = FALSE)

2. Find Total Rows and Columns:

dim(emp)

3. Find Maximum Salary:

max(emp$Salary)

4. Employee with Maximum Salary:

emp[which.max(emp$Salary), ]

5. Employees in IT Department with Salary > 20,000:

subset(emp, Department == "IT" & Salary > 20000)

6. All Employees in IT Department:

subset(emp, Department == "IT")


OR Q6:

a. Grouping functions with examples:

1. apply(): Applies a function over matrix margins.


Example:

mat <- matrix(1:9, nrow = 3)

apply(mat, 1, sum) # Row-wise sum

2. lapply(): Applies a function to each element of a list.


Example:

l <- list(a = 1:3, b = 4:6)

lapply(l, sum)

3. mapply(): Multivariate version of lapply.


Example:

mapply(sum, 1:3, 4:6)

4. rapply(): Recursive version of lapply.


Example:

l <- list(a = 1:3, b = list(c = 4:6))

rapply(l, sum, how = "list")

5. tapply(): Applies a function over subsets of a vector.


Example:

tapply(1:10, rep(1:2, each = 5), sum)

b. Importing and exporting unstructured files:

1. Import a CSV file:

data <- read.csv("file.csv")

2. Export a data frame to CSV:

write.csv(data, "output.csv")

3. Import an Excel file using the readxl package:

library(readxl)
data <- read_excel("file.xlsx")

4. Export to Excel using writexl:

library(writexl)

write_xlsx(data, "output.xlsx")

Module-4

Q7:

a. Create a pie chart for flower data:

1. Basic Syntax:

pie(x, labels, main, col, ...)

2. Parameters:

o x: Numeric vector of data.

o labels: Labels for each section.

o main: Chart title.

o col: Colors for slices.

3. Example:

flowers <- c(25, 35, 10, 5, 15)

labels <- c("Rose", "Lotus", "Lily", "Sunflower", "Jasmine")

pie(flowers, labels, main = "Flower Distribution", col = rainbow(length(flowers)))

b. Ways to create scatter plots:

1. Base R:

plot(x, y, main, xlab, ylab, col, ...)

2. ggplot2:

library(ggplot2)
ggplot(data, aes(x = var1, y = var2)) + geom_point()

OR Q8:

a. Vertical and horizontal bar plots:

1. Vertical Bar Plot:

barplot(height, names.arg, col, main, ...)

2. Horizontal Bar Plot:

barplot(height, names.arg, col, horiz = TRUE, ...)

Example:

values <- c(5, 10, 15)

names <- c("A", "B", "C")

barplot(values, names.arg = names, col = "blue", main = "Bar Plot")

b. Graphing functions:

1. hist():

hist(x, main, xlab, ...)

2. plot():

plot(x, y, main, xlab, ylab, ...)

3. boxplot():

boxplot(data, main, ...)

4. bwplot(): (Lattice package)

library(lattice)

bwplot(var ~ factor, data)

5. ggplot():

library(ggplot2)

ggplot(data, aes(x, y)) + geom_boxplot()


Module-5

Q9:

a. Basic statistical measures with examples:

1. Mean, Median, Mode, SD, Variance:

x <- c(45, 56, 78, 12, 3, -91, 45, 15, 1, 24)

mean(x)

median(x)

sd(x)

var(x)

b. Normal Distribution in R:

1. Functions:

o dnorm: Density function.

o pnorm: Cumulative probability.

o rnorm: Random generation.

o qnorm: Quantile function.

2. Example:

x <- rnorm(1000, mean = 50, sd = 10)

hist(x)

OR Q10:

a. Analyze the mtcars dataset:

1. Correlation between hp and mpg:


cor(mtcars$hp, mtcars$mpg)

plot(mtcars$hp, mtcars$mpg)

2. Correlation between hp and disp:

cor(mtcars$hp, mtcars$disp)

plot(mtcars$hp, mtcars$disp)

3. Analyze all correlations:

cor(mtcars)

b. Linear regression analysis:

1. Example:

model <- lm(mpg ~ hp + wt, data = mtcars)

summary(model)

You might also like