R programming
Task 1a and 1b: Arrays with Different Length Vectors
Theory:
Arrays in R are multi-dimensional data structures used to store data in
rows, columns, and layers.
When combining vectors of different lengths, R recycles elements from
shorter vectors to match the dimensions.
You can access specific elements or slices of the array using indexing.
Key Points:
dimsets the dimensions of the array (e.g., dim = c(3,3,2) creates a 3x3x2
array).
Indexing [2,,2] accesses the second row across all columns in the second
layer.
Task 2a: Sum, Mean, and Product
Theory:
Operations like sum, mean, and product compute aggregate properties of
numeric vectors.
adds all elements, mean() calculates the average, and
sum() prod()
computes the product of all elements.
Key Points:
These are basic mathematical functions that are widely used in statistical
computations.
Task 2b: Prime Number Check
Theory:
R programming 1
A prime number is greater than 1 and divisible only by 1 and itself.
The function iterates from 2 to to check if the number is divisible by any
integer.
n−1n-1
Returns TRUE for prime numbers and FALSE otherwise.
Task 3a: Sequence and Mathematical Functions
Theory:
Functions like seq() , mean() , sum() , abs() , and trigonometric/logarithmic
functions perform basic mathematical and statistical operations.
Examples:
seq(32,44) generates a sequence from 32 to 44.
mean(25:82) calculates the average of numbers from 25 to 82.
round() rounds numbers to the specified decimal places.
log() computes the natural logarithm.
Task 3b: Factors of a Number
Theory:
A factor of a number divides without leaving a remainder.
nn
nn
The loop checks divisibility using the modulus operator ( %% ).
Task 4a: Fibonacci Sequence
Theory:
The Fibonacci sequence starts with 0 and 1, and each subsequent number
is the sum of the previous two.
A recursive function is used, where .
R programming 2
F(n)=F(n−1)+F(n−2)F(n) = F(n-1) + F(n-2)
Task 4b: Sum of Natural Numbers
Theory:
The sum of the first natural numbers can be computed using recursion or
the formula .
nn
S=n(n+1)2S = \frac{n(n+1)}{2}
The recursive function sums numbers from down to 1.
nn
Task 5: Random Numbers and Tables
Theory:
rnorm(n, mean, sd) generates n random numbers from a normal distribution.
table() counts occurrences of unique values in a vector.
plot() creates visualizations.
Key Points:
Normal distribution is fundamental in statistics, and visualization is useful
for analyzing data.
Task 6a and 6b: Matrix Addition and Multiplication
Theory:
Matrices are two-dimensional arrays, and arithmetic operations can be
performed on them element-wise.
Addition: Adds corresponding elements.
Multiplication: Performs element-wise multiplication (not matrix product).
Key Points:
Dimensions must match for operations.
R programming 3
Use %*% for matrix multiplication (dot product).
Task 7: Data Frame
Theory:
A data frame is a table-like structure where each column can have
different types.
Used to store and manipulate datasets in R.
Key Points:
Columns are accessible by name, e.g., [Link]$name .
Data frames support tabular operations and visualization.
Task 8: Employee Data and Summary
Theory:
summary() provides descriptive statistics for each column in a data frame.
Useful for understanding the central tendency, spread, and distribution of
data.
Task 9: Data Imputation, Normalization, Encoding, and Outlier
Removal
Theory:
Imputation: Filling missing values using statistical techniques like mean
imputation.
Normalization: Scaling values to a range (e.g., [0, 1]) to make features
comparable.
One-Hot Encoding: Converts categorical variables into numeric binary
variables.
Outlier Removal: Removes data points outside the interquartile range (IQR)
for robust analysis.
R programming 4
Task 10a: ggplot2 Visualizations
Theory:
ggplot2 is a powerful R package for creating static and interactive
visualizations.
Scatter plots, bar charts, and smoothed trend lines help analyze
relationships and distributions.
Key Points:
geom_point() for scatter plots.
geom_smooth() for trend lines.
geom_bar() for bar charts.
Task 10b: Hypothesis Testing (t-test)
Theory:
A t-test compares a sample mean to a known value or another sample
mean.
Null hypothesis (): No significant difference between the means.
H0H_0
p-value < 0.05 indicates rejecting .
H0H_0
Key Points:
One-sample t-test checks if a sample mean differs from a population
mean.
Task 11: Simple Linear Regression
Theory:
Linear regression models the relationship between a dependent variable
(e.g., Salary) and an independent variable (e.g., YearsExperience).
R programming 5
SSE (Sum of Squared Errors): Measures the total deviation of predictions
from actual values.
SSR (Sum of Squares for Regression): Measures the variation explained
by the model.
SST (Total Sum of Squares): Total variation in the dataset.
Key Points:
Visualization compares predictions and actual values to assess model
performance.
Task 1a
print("Two vectors of different length")
v1 <- c(1, 3, 4, 5)
v2 <- c(seq(10, 15))
print(v1)
print(v2)
result <- array(c(v1, v2), dim = c(3, 3, 2))
print("New array:")
print(result)
print(result[2, , 2])
Task 1b
print("Two vectors of different length")
v1 <- c(1, 3, 4, 5)
v2 <- c(seq(10, 15))
print(v1)
print(v2)
result <- array(c(v1, v2), dim = c(3, 3, 2))
print("New array:")
print(result)
print(result[2, , 2])
R programming 6
Task 2a
v1 <- c(10, 20, 30, 40, 50)
print(paste("Sum is", sum(v1)))
print(paste("Mean is", mean(v1)))
print(paste("Prod is", prod(v1)))
Task 2b
isprime <- function(n1) {
if (n1 == 2) {
return(TRUE)
}
if (n1 <= 1) {
return(FALSE)
}
for (i in 2:(n1 - 1)) {
if (n1 %% i == 0) {
return(FALSE)
}
}
return(TRUE)
}
n <- 13
if (isprime(n)) {
print("TRUE")
} else {
print("FALSE")
}
Task 3a
print(seq(32, 44))
print(mean(25:82))
print(sum(41:58))
R programming 7
print(abs(-1000))
print(round(5.67, digits = 1))
print(cos(60))
print(log(1000))
print(floor(49.567))
Task 3b
n <- 15
print("Factors of n are:")
for (i in 1:n) {
if (n %% i == 0) {
print(i)
}
}
Task 4a
fib <- function(n) {
if (n == 0)
return(0)
if (n == 1)
return(1)
else
return(fib(n - 1) + fib(n - 2))
}
n <- 10
for (i in 0:n) {
print(fib(i))
}
Task 4b
nsum <- function(n) {
if (n == 0)
R programming 8
return(0)
if (n == 1)
return(1)
else
return(nsum(n - 1) + n)
}
print(nsum(10))
Task 5
n <- floor(rnorm(4, 0, 1))
print("List of random numbers in normal distribution:")
print(n)
t <- table(n)
print("Count occurrences of each value:")
print(t)
plot(1:10)
rnorm()
mtcars
x <- c(10, 10, 6, 9, 7, 7, 7, 8, 8, 5)
print(table(x))
Task 6a
m1 <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2)
print("Matrix -1:")
print(m1)
m2 <- matrix(c(0, 1, 2, 2, 0, 2), nrow = 2)
print("Matrix -2:")
print(m2)
result <- m1 + m2
print("Result of addition")
print(result)
R programming 9
Task 6b
m1 <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2)
print("Matrix -1:")
print(m1)
m2 <- matrix(c(0, 1, 2, 3, 0, 2), nrow = 2)
print("Matrix -2:")
print(m2)
result <- m1 %*% m2
print("Result of multiplication")
print(result)
Task 7
name <- c("f", "As", "Ag", "Agrh")
rollno <- c(221, 223, 225, 220)
subname <- c("DEVC", "EC", "RPL", "GE")
marks <- c(98, 90, 94, 90)
[Link] <- [Link](name, rollno, subname, marks)
print([Link])
Task 8
[Link] <- [Link](
id = c(1:5),
ename = c("Rick", "Dan", "Michelle", "Ryan", "Gary"),
salary = c(623.3, 517.2, 611.0, 729.0, 843.25),
gender = c("M", "M", "F", "M", "M")
)
print([Link])
print(summary([Link]))
Task 9
R programming 10
library(tidyverse)
library(caret)
library(dplyr)
library(ggplot2)
[Link](123)
data <- [Link](
Age = c(25, 30, NA, 22, 35, 28, 45, 40, NA, 32),
Salary = c(50000, 60000, 58000, NA, 80000, 62000, 75000, 68000, 70000,
72000),
Gender = c("Male", "Female", "Female", "Male", "Male", "Female", "Female",
"Male", "Female", "Male")
)
print("Original Data:")
print(data)
data <- data %>%
mutate(
Age = ifelse(
[Link](Age), mean(Age, [Link] = TRUE), Age),
Salary = ifelse(
[Link](Salary), mean(Salary, [Link] = TRUE), Salary)
)
print("Data After imputation")
print(data)
data$Normalized_Salary <- (data$Salary - min(data$Salary)) / (max(data$Salary) -
min(data$Salary))
print("Data after normalization")
print(data)
dummy_model <- dummyVars("~ Gender", data = data)
data_encoded <- predict(dummy_model, newdata = data) %>% [Link]()
data <- cbind(data_encoded, data[, c("Age", "Normalized_Salary")])
print("Data after One-Hot encoding")
print(data)
Q1 <- quantile(data$Age, 0.25)
Q3 <- quantile(data$Age, 0.75)
R programming 11
IQR <- Q3 - Q1
data <- data %>%
filter(Age >= (Q1 - 1.5 * IQR) & Age <= (Q3 + 1.5 * IQR))
print("Data After Outlier Removal:")
print(data)
Task 10a
library(ggplot2)
data(iris)
ggplot(iris, aes(x = [Link], y = [Link])) + geom_point()
ggplot(iris, aes(x = [Link], y = [Link], col = Species, shape =
Species)) + geom_point()
ggplot(iris, aes(x = [Link], y = [Link], col = Species)) + geom_point()
+ geom_smooth()
ggplot(mtcars, aes(x = gear)) + geom_bar()
ggplot(mtcars, aes(hp, mpg)) + geom_point(color = "blue") + stat_summary(fun.y
= "mean", geom = "line", linetype = "dashed")
Task 10b
test_scores <- c(52, 47, 58, 60, 45, 48, 51, 53, 49, 46)
null_mean <- 50
t_test_result <- [Link](test_scores, mu = null_mean)
print(t_test_result)
if (t_test_result$[Link] < 0.05) {
print("Reject the null hypothesis: The mean is significantly different from 50.")
} else {
print("Fail to reject the null hypothesis: There is no significant difference from
50.")
}
Task 11
R programming 12
library(ggplot2)
library(caTools)
dataset <- [Link]("C:/Users/mohan/Desktop/rp internal/Salary_Data.csv")
dataset$YearsExperience
dataset$Salary
split <- [Link](dataset$Salary, SplitRatio = 0.7)
trainingset <- subset(dataset, split == TRUE)
testset <- subset(dataset, split == FALSE)
lm.r <- lm(formula = Salary ~ YearsExperience, data = trainingset)
print(summary(lm.r))
print(coef(lm.r))
sse <- sum((fitted(lm.r) - trainingset$Salary)^2)
ssr <- sum((fitted(lm.r) - mean(trainingset$Salary))^2)
sst <- ssr + sse
print(sst)
ypred <- predict(lm.r, newdata = testset)
print(summary(ypred))
ggplot() +
geom_point(aes(x = trainingset$YearsExperience, y = trainingset$Salary), color =
"red") +
geom_line(aes(x = trainingset$YearsExperience, y = predict(lm.r, newdata =
trainingset)), color = "blue") +
ggtitle("Salary vs YearsExp (training set)") +
xlab("YearsExperience") +
ylab("Salary")
ggplot() +
geom_point(aes(x = testset$YearsExperience, y = testset$Salary), color = "red") +
geom_line(aes(x = trainingset$YearsExperience, y = predict(lm.r, newdata =
trainingset)), color = "blue") +
ggtitle("Salary vs YearsExp (test set)") +
xlab("YearsExperience") +
ylab("Salary")
R programming 13