R PROGRAMMING LAB
PART - A
Suhas B Raj, Asst [Link] of CA, MITFGC, Mysuru Page 1 | 15
R PROGRAMMING LAB
1. Write a R Program to implement operations of Set (Union, Intersection, Differ
ence, Subset).
set1 <- c(1, 2, 3, 4, 5)
set2 <- c(4, 5, 6, 7, 8)
cat("Union of set1 and set2: ", union(set1, set2), "\n")
cat("Intersection of set1 and set2: ", intersect(set1, set2), "\n")
cat("Difference of set1 and set2 (set1 - set2): ", setdiff(set1, set2), "\n")
cat("Is set1 a subset of set2? ", all(set1 %in% set2), "\n")
OUTPUT:
Union of set1 and set2: 1 2 3 4 5 6 7 8
Intersection of set1 and set2: 4 5
Difference of set1 and set2 (set1 - set2): 1 2 3
Is set1 a subset of set2? FALSE
2. Write a R program to implement inverse function.
inverse = function (f, L = 0, U = 10) {
function(y) {
g <- function(x) f(x) - y
result <- uniroot(g, lower = L, upper = U)
return(result$root)
square_inverse = inverse(function(x) x^2, 0.1, 100)
cat("The inverse of 16 is approximately", square_inverse(16), "\n")
OUTPUT: The inverse of 16 is approximately 4.000011
uniroot() function for finding roots of equations, which can help in finding the inverse.
f: A continuous function for which the root is to be found.
lower: The lower end of the interval (default is the minimum of the interval vector).
Suhas B Raj, Asst [Link] of CA, MITFGC, Mysuru Page 2 | 15
R PROGRAMMING LAB
upper: The upper end of the interval (default is the maximum of the interval vector).
Simple function:ƒ (x)=x2.
Creating Inverse: The inverse function is called with ƒ and the interval [0.1, 100] to create
square_inverse, a function that computes the inverse of ƒ.
3. Write a R Program to implement one-to-one function.
one_to <- function(x) {
return(2 * x + 3)
}
is_one<- function(f, d) {
v<- sapply(d, f)
return(length(v) == length(unique(v)))
}
d <- seq(-10, 10, by = 0.1)
if (is_one(one_to, d)) {
cat("The function is one-to-one over the specified domain.\n")
} else {
cat("The function is not one-to-one over the specified domain.\n")
}
test_values<-c(-5,0,5)
cat("Test values:", test_values,"\n")
cat("Function results:", sapply(test_values, one_to), "\n")
OUTPUT:
The function is one-to-one over the specified domain.
Test values: -5 0 5
Function results: -7 3 13
sapply () in R is a variant of apply family functions that applies a function to each element of a list or
vector and simplifies the result. When you use sapply (domain, f), it applies the function f to each
element of the domain vector and returns a vector or matrix (if possible) of the results.
domain: A vector of values over which you want to apply the function f.
Suhas B Raj, Asst [Link] of CA, MITFGC, Mysuru Page 3 | 15
R PROGRAMMING LAB
f: The function you want to apply to each element of domain.
4. Write a R Program to implement Cartesian Product of Two sets.
cart<- function(set1, set2) {
re<-list()
for (a in set1) {
for (b in set2) {
re <-c(re,list(c(a, b)))
return(re)
set1 <- c("A", "B")
set2 <- c(1, 2)
print(cart(set1, set2))
OUTPUT
[[1]] [1] "A" "1"
[[2]] [1] "A" "2"
[[3]] [1] "B" "1"
[[4]] [1] "B" "2"
Purpose: Computes the Cartesian product of two sets set1 and set2.
Input: Takes two vectors set1 and set2 as arguments.
Output: Returns a list containing all ordered pairs (a, b) where a is from set1 and b is from set2.
Suhas B Raj, Asst [Link] of CA, MITFGC, Mysuru Page 4 | 15
R PROGRAMMING LAB
5. Write a R Program to check whether the given relation is Reflexive.
# Function to check if a relation is reflexive
reflexive <- function(ele, rel) {
for(e in ele) {
if (!any(sapply(rel, function(x) identical(x, c(e, e))))) {
return(FALSE)
return(TRUE)
# Elements in the set
ele <- c("a", "b", "c")
# Relation represented as pairs in a list
rel <- list(c("a", "a"), c("b", "b"), c("c", "c"))
# Check if the relation is reflexive
if (reflexive(ele, rel)) {
cat("The relation is reflexive.\n")
} else {
cat("The relation is not reflexive.\n")
OUTPUT: The relation is reflexive.
Suhas B Raj, Asst [Link] of CA, MITFGC, Mysuru Page 5 | 15
R PROGRAMMING LAB
6. Write a R Program to check whether the given relation is Transitive.
transitive <- function(rel) {
for (p in rel) {
for (q in rel) {
if (p[2] == q[1]) {
new_pair <- c(p[1], q[2])
if (!any(sapply(rel, function(pair) all(pair == new_pair)))) {
return(FALSE) }}}}
return(TRUE) }
rel<- list(c("a", "b"),c("b", "c"),c("a", "c"))
if (transitive(rel)) {
cat("The relation is transitive.\n")
} else {
cat("The relation is not transitive.\n")
OUTPUT: The relation is transitive.
7. Write a R Program to implement logic gates (NOT, AND, OR, XOR).
x <- TRUE
y <- FALSE
cat("NOT(x): ", !x, "\n")
cat("AND(x, y): ", x & y, "\n")
cat("OR(x, y): ", x | y, "\n")
cat("XOR(x, y): ", x != y, "\n")
OUTPUT:
NOT(x): FALSE
Suhas B Raj, Asst [Link] of CA, MITFGC, Mysuru Page 6 | 15
R PROGRAMMING LAB
AND(x, y): FALSE
OR(x, y): TRUE
XOR(x, y): TRUE
8. Write a R Program to check whether the given relation is Symmetric.
symmetric <- function(rel) {
n <- length(rel)
for (i in 1:n) {
x <- rel[[i]]
rev <- c(x[2], x[1])
if (!(any(sapply(rel, function(x) identical(x, rev))))) {
return(FALSE)
return(TRUE)
rel <- list(c("a", "b"),c("b", "a"),c("c", "c"))
if (symmetric(rel)) {
cat("The relation is symmetric.\n")
} else {
cat("The relation is not symmetric.\n")
OUTPUT: The relation is symmetric.
Suhas B Raj, Asst [Link] of CA, MITFGC, Mysuru Page 7 | 15
R PROGRAMMING LAB
PART - B
Suhas B Raj, Asst [Link] of CA, MITFGC, Mysuru Page 8 | 15
R PROGRAMMING LAB
1. Write a R Program to Calculate central tendency (mean, median, mode).
data <- c(1, 2, 2, 3, 4, 5,5,5, 6, 7, 8, 9, 10)
uniqv <- unique(data)
freq <- tabulate(match(data, uniqv))
mode_value <- uniqv[[Link](freq)]
cat("Mean: ", mean(data), "\n")
cat("Median: ", median(data), "\n")
cat("Mode: ", mode_value, "\n")
OUTPUT:
Mean: 5.153846
Median: 5
Mode: 5
2. Write a R Program to Calculate standard deviation and variance for discrete &
continuous series.
# standard deviation and variance for discrete series.
data <- c(1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10)
cat("Discrete Series - Variance: ",var(data), "\n")
cat("Discrete Series - Standard Deviation: ", sd(data), "\n")
OUTPUT:
Discrete Series - Variance: 9.363636
Discrete Series - Standard Deviation: 3.060006
# standard deviation and variance for continuous series.
class_intervals <- c("0-10", "10-20", "20-30")
frequencies <- c(5, 15, 10)
Suhas B Raj, Asst [Link] of CA, MITFGC, Mysuru Page 9 | 15
R PROGRAMMING LAB
midpoints <- c(5, 15, 25)
n <- sum(frequencies)
mean_val <- sum(midpoints * frequencies) / n
variance <- sum(frequencies * (midpoints - mean_val)^2) / (n - 1)
std_dev <- sqrt(variance)
cat("Continuous Series - Variance: ", variance, "\n")
cat("Continuous Series - Standard Deviation: ", std_dev, "\n")
OUTPUT:
Continuous Series - Variance: 48.85057
Continuous Series - Standard Deviation: 6.989319
3. Write a R Program to Calculate coefficient of variance for discrete & continuous
series.
# coefficient of variance for discrete series.
discrete_data <- c(1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10)
mean_value <- mean(data)
std_dev <- sd(data)
cv <- (std_dev / mean_value) * 100
cat("Discrete Series - Coefficient of Variance: ", cv, "%\n")
OUTPUT: Discrete Series - Coefficient of Variance: 59.05275 %
# coefficient of variance for continuous series.
class_intervals <- c("0-10", "10-20", "20-30")
frequencies <- c(5, 15, 10)
midpoints <- c(5, 15, 25)
n <- sum(frequencies)
mean_val <- sum(midpoints * frequencies) / n
Suhas B Raj, Asst [Link] of CA, MITFGC, Mysuru Page 10 | 15
R PROGRAMMING LAB
variance <- sum(frequencies * (midpoints - mean_val)^2) / (n - 1)
std_dev <- sqrt(variance)
cv <- (std_dev / mean_val) * 100
cat("Continuous Series - Coefficient of Variance: ", cv, "%\n")
OUTPUT: Continuous Series - Coefficient of Variance: 41.93591 %
4. Write a R Program to Calculate simple Linear Algebra Operations.
A <- matrix(c(1, 2, 3, 4), nrow=2, byrow=TRUE)
B <- matrix(c(9, 8, 7, 6), nrow=2, byrow=TRUE)
#Addition of two matrix A + B
print(A + B)
OUTPUT: [,1] [,2]
[1,] 10 10
[2,] 10 10
#Subtraction of two matrix A - B
print(A - B)
OUTPUT: [,1] [,2]
[1,] -8 -6
[2,] -4 -2
#Multiplication of matrix A X B
print(A%*%B)
OUTPUT: [,1] [,2]
[1,] 23 20
[2,] 55 48
Suhas B Raj, Asst [Link] of CA, MITFGC, Mysuru Page 11 | 15
R PROGRAMMING LAB
#Transposition of matrix A:
print(t(A))
OUTPUT: [,1] [,2]
[1,] 1 3
[2,] 2 4
# Determinate of Matrix A:
print(det(A))
OUTPUT: [1] -2
#Inverse of Matrix A:
print(solve(A))
OUTPUT: [,1] [,2]
[1,] -2.0 1.0
[2,] 1.5 -0.5
5. Write a R Program to Calculate arithmetic mean for grouped and ungrouped
data.
data <- c(10, 15, 20, 25, 30) # Ungrouped data
mean_ungrp <- mean(data) # Calculate mean
cat("Arithmetic Mean for Ungrouped Data:",mean_ungrp) # Display mean
values <- c(10, 20, 30, 40)
frequencies <- c(5, 10, 15, 20)
mean_grp <- sum(values * frequencies) / sum(frequencies) # Calculate mean
cat("Arithmetic Mean for Grouped Data:",mean_grp) # Display mean
OUTPUT:
Arithmetic Mean for Ungrouped Data: 20
Arithmetic Mean for Grouped Data: 30
Suhas B Raj, Asst [Link] of CA, MITFGC, Mysuru Page 12 | 15
R PROGRAMMING LAB
6. Write a R Program to Calculate cumulative sums, and products, minima,
maxima.
numbers <- c (1, 2, 3, 4, 5) # Sample vector of numbers
cat ("Cumulative Sum:", cumsum(numbers),"\n") # Calculate cumulative sum
OUTPUT: Cumulative Sum: 1 3 6 10 15
cat("Cumulative Product:", cumprod(numbers) , "\n") #Calculate cumulative product
OUTPUT: Cumulative Product: 1 2 6 24 120
cat ("Minimum:", min(numbers),"\n") # Calculate minimum and maximum
cat ("Maximum:", max(numbers),"\n")
OUTPUT: Minimum:1 Maximum:5
7. Write a R Program to Calculate frequency distribution for discrete & continuous
series.
# Define discrete and continuous data
discrete_data <- c(1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 6)
continuous_data <- c(1.5, 2.3, 2.8, 3.1, 3.6, 4.0, 4.4, 4.8, 5.2, 5.7, 6.1, 6.5, 7.0)
# Define class intervals for continuous data
class_intervals <- seq(1, 8, by = 1)
# Calculate and print frequency distribution for discrete data
freq_discrete <- table(discrete_data)
cat("Frequency Distribution for Discrete Data:\n")
print([Link](freq_discrete))
OUTPUT: Frequency Distribution for Discrete Data:
data Freq
1 1 2
2 2 3
Suhas B Raj, Asst [Link] of CA, MITFGC, Mysuru Page 13 | 15
R PROGRAMMING LAB
3 3 3
4 4 3
5 5 2
6 6 1
# Calculate and print frequency distribution for continuous data
data_cut <- cut(continuous_data, breaks = class_intervals, right = FALSE)
freq_continuous <- table(data_cut)
cat("Frequency Distribution for Continuous Data:\n")
print([Link](freq_continuous))
OUTPUT: Frequency Distribution for Continuous Data:
data Freq
1 [1,2) 1
2 [2,3) 2
3 [3,4) 2
4 [4,5) 3
5 [5,6) 2
6 [6,7) 2
7 [7,8) 1
8. Write a R Program to Calculate Simple Linear Regression.
# Load the dataset
data <- mtcars # Using the built-in mtcars dataset as an example
# Define the independent variables (features)
independent_variables <- c("disp", "hp", "wt", "qsec")
# Define the dependent variable
Suhas B Raj, Asst [Link] of CA, MITFGC, Mysuru Page 14 | 15
R PROGRAMMING LAB
dependent_variable <- "mpg"
# Build the multivariate linear regression model
model <- lm(formula = paste(dependent_variable, "~", paste(independent_variables, collapse = " + "))
, data = data)
# Summary of the model
summary(model)
OUTPUT:
Residuals:
Min 1Q Median 3Q Max
-3.8664 -1.5819 -0.3788 1.1712 5.6468
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 27.329638 8.639032 3.164 0.00383 **
disp 0.002666 0.010738 0.248 0.80576
hp -0.018666 0.015613 -1.196 0.24227
wt -4.609123 1.265851 -3.641 0.00113 **
qsec 0.544160 0.466493 1.166 0.25362
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 2.622 on 27 degrees of freedom
Multiple R-squared: 0.8351, Adjusted R-squared: 0.8107
F-statistic: 34.19 on 4 and 27 DF, p-value: 3.311e-10
Suhas B Raj, Asst [Link] of CA, MITFGC, Mysuru Page 15 | 15