GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
SL PAGE
PROGRAM NAME REMARKS
NO NO
PART – A
1. Write a R program for different types of data structures in R.
2. Write a R program that include variables, constants, data types.
Write a R program that include different operators, control
3. structures, default values for arguments, returning complex
objects.
Write a R program for quick sort implementation, binary search
4.
tree.
Write a R program for calculating cumulative sums, and products
5
minima maxima and calculus.
Write a R program for finding stationary distribution of markanov
6
chains.
Write a R program that include linear algebra operations on
7
vectors and matrices.
Write a R program for any visual representation of an object with
creating Graphs using graphic functions: plot(), hist(), line chart(),
8
pie(), box plot(), Scatter plots().
Write a R program for with any dataset containing data frame
objects, indexingand sub setting data frames, and employ
9
manipulating and analyzing data.
Write a R program to create any application of linear regression in
10 multivariate context for predictive purpose.
write a R program to take input from the user (name and age) and
11 display the values. Also print the version of r installation
STAFF INCHARGE
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
PART –B
1 Write a R program to get the details of the objects in memory.
Write a R program to create a sequence of numbers from 20 to 50
and find the mean of numbers from 20 to 60 and sum of numbers
2
from 51 to 91.
Write a R program to create a vector which contains 10 random
3
integer values between -50 and +50.
4 Write a R program to get the first 10 fibonacci numbers.
Write a R program to get all prime numbers up to a given number
5
(based on the sieve of eratosthenes).
Write a R program to print the numbers from 1 to 100 and print
6 "fizz" for multiples of 3, print "buzz" for multiples of 5, and print
"fizz buzz" for multiples of both.
Write a R program to extract first 10 english letter in lower case
7 and last 10 letters in upper case and extract letters between 22nd
to 24thletters in upper case.
8 Write a R program to find the factors of a given number.
Write a R program to find the maximum and the minimum value of
9
a given vector.
Write a R program to get the unique elements of a given string and
10
unique numbers of vector.
Write a R program to create three vectors a,b,c with 3 integers.
11 Combine the three vectors to become a 3x3 matrix where each
column represents a vector. Print the content of the matrix.
STAFF INCHARGE
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
1. Write a R program for different types of data structures in R.
# Vector
my_vector <- c(1, 2, 3, 4, 5)
print("Vector:")
print(my_vector)
# List
my_list <- list(name = "John", age = 30, city = "New York")
print("List:")
print(my_list)
# Matrix
my_matrix <- matrix(1:6, nrow = 2, ncol = 3)
print("Matrix:")
print(my_matrix)
# Data Frame
my_df <- data.frame(Name = c("Alice", "Bob", "Charlie"), Age = c(25, 30, 22))
print("Data Frame:")
print(my_df)
# Array
my_array <- array(1:12, dim = c(2, 3, 2))
print("Array:")
print(my_array)
# Factor
my_factor <- factor(c("High", "Low", "Medium", "High", "Low"))
print("Factor:")
print(my_factor)
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
OUTPUT:
[1] "Vector:"
[1] 1 2 3 4 5
[1] "List:"
$name
[1] "John"
$age
[1] 30
$city
[1] "New York"
[1] "Matrix:"
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
[1] "Data Frame:"
Name Age
1 Alice 25
2 Bob 30
3 Charlie 22
[1] "Array:"
,,1
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
,,2
[,1] [,2] [,3]
[1,] 7 9 11
[2,] 8 10 12
[1] "Factor:"
[1] High Low Medium High Low
Levels: High Low Medium
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
2. Write an r program that includes variables, constants, data types.
# Constants
PI <- 3.14159
PLANET <- "Earth"
# Variables
radius <- 5
name <- "John Doe"
age <- 30
is_student <- TRUE
# Display constants and variables
cat("Constants:\n")
cat("PI:", PI, "\n")
cat("PLANET:", PLANET, "\n\n")
cat("Variables:\n")
cat("Radius:", radius, "\n")
cat("Name:", name, "\n")
cat("Age:", age, "\n")
cat("Is student?:", is_student, "\n\n")
# Data types
cat("Data types:\n")
cat("Type of PI:", typeof(PI), "\n")
cat("Type of radius:", typeof(radius), "\n")
cat("Type of name:", typeof(name), "\n")
cat("Type of age:", typeof(age), "\n")
cat("Type of is_student:", typeof(is_student), "\n")
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
OUTPUT:
Constants:
PI: 3.14159
PLANET: Earth
Variables:
Radius: 5
Name: John Doe
Age: 30
Is student?: TRUE
Data types:
Type of PI: double
Type of radius: double
Type of name: character
Type of age: double
Type of is_student: logical
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
3. Write a r program that include different operators, control structures, default values for
arguments, returning complex objects.
#Function with default values for arguments
calculate_area <-function(radius=5, shape='circle')
{
if(shape=='circle')
{
area<-pi*radius*2
}
else if(shape=='square')
{
area<-radius*2
}
else
{
cat("Unsupported shape", shape, "\n")
return(NULL)
}
#Conditional Operator
msg<-ifelse(area>10,"Large Area", "Small Area")
#Returning complex object
return(list(shape=shape,radius=radius,area=area,msg=msg))
}
#usage
circle_result<-calculate_area()
#using default values
square_result<-calculate_area(radius=4, shape='square')
#display result
cat("Circle Result","\n")
print(circle_result)
cat("Square Result","\n")
print(square_result)
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
OUTPUT:
Circle Result
$shape
[1] "circle"
$radius
[1] 5
$area
[1] 31.41593
$msg
[1] "Large Area"
Square Result
$shape
[1] "square"
$radius
[1] 4
$area
[1] 8
$msg
[1] "Small Area"
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
4. Write a r program for quick sort implementation, binary search tree.
# Quick Sort function
quick_sort <- function(arr)
{
if (length(arr) <= 1)
{
return(arr)
}
pivot <- arr[1]
less <- arr[arr < pivot]
equal <- arr[arr == pivot]
greater <- arr[arr > pivot]
return(c(quick_sort(less), equal, quick_sort(greater)))
}
# Example usage
unsorted_array <- c(9, 7, 5, 11, 12, 2, 14, 3, 10, 6)
sorted_array <- quick_sort(unsorted_array)
cat("QUICK SORT is in Sorted Array :", sorted_array, "\n")
# Define a Node structure for the Binary Search Tree
Node <- function(key) {
return(list(key = key, left = NULL, right = NULL))
}
# Insert a value into the BST
insert <- function(root, key)
{
if (is.null(root))
{
return(Node(key))
}
if (key < root$key)
{
root$left <- insert(root$left, key)
}
else if (key > root$key)
{
root$right <- insert(root$right, key)
}
return(root)
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
# In-order traversal to print BST elements in sorted order
inorder_traversal <- function(root)
{
if (!is.null(root))
{
inorder_traversal(root$left)
cat(root$key, " ")
inorder_traversal(root$right)
}
}
# Example usage
bst_root <- NULL
bst_root <- insert(bst_root, 10)
bst_root <- insert(bst_root, 5)
bst_root <- insert(bst_root, 15)
bst_root <- insert(bst_root, 3)
bst_root <- insert(bst_root, 7)
bst_root <- insert(bst_root, 12)
bst_root <- insert(bst_root, 18)
cat("BINARY SEARCH TREE >>> In-order Traversal (Sorted Order): ")
inorder_traversal(bst_root)
OUTPUT:
QUICK SORT is in Sorted Array : 2 3 5 6 7 9 10 11 12 14
BINARY SEARCH TREE >>> In-order Traversal (Sorted Order): 3 5 7 10 12 15 18
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
5. Write an r program for calculating cumulative sums and products, minima, maxima and
calculus.
# Create a vector of numbers
numbers <- c(2, 4, 1, 8, 5, 7)
# Calculate the cumulative sum
cumulative_sum <- cumsum(numbers)
cat("Cummulative Sum:",cumulative_sum,"\n")
# Calculate the cumulative product
cumulative_product <- cumprod(numbers)
cat("Cummulative Product:",cumulative_product,"\n")
# Find the minimum and maximum values
minimum_value <- min(numbers)
maximum_value <- max(numbers)
cat("Minimum Value", minimum_value, "\n")
cat("Maximum Value", maximum_value, "\n")
# Calculus Differentiation
differentiate<-diff(numbers)
cat("Differentiation (First Difference):", differentiate,"\n")
# Calculus Integration
integrate<-cumsum(numbers)
cat("Integration (Cummulative Sum):",integrate, "\n")
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
OUTPUT:
Cummulative Sum: 2 6 7 15 20 27
Cummulative Product: 2 8 8 64 320 2240
Minimum Value 1
Maximum Value 8
Differentiation (First Difference): 2 -3 7 -3 2
Integration (Cummulative Sum): 2 6 7 15 20 27
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
6. Write an r program for finding stationary distribution of markanov chains
# Install and load the markovchain package
install.packages("markovchain")
library(markovchain)
# Create a transition matrix for the Markov chain
transition_matrix <- matrix(c(0.7, 0.3, 0.2, 0.8), nrow = 2, byrow = TRUE)
# Create a markovchain object
mc <- new("markovchain", states = c("State1", "State2"), transitionMatrix =
transition_matrix)
# Find the stationary distribution
stationary_dist <- steadyStates(mc)
# Print the stationary distribution
print(stationary_dist)
OUTPUT
State1 State2
[1,] 0.4 0.6
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
7. Write an r program that includes linear algebra operations on vectors and matrices.
# Create vectors
vector1 <- c(1, 2, 3)
vector2 <- c(4, 5, 6)
# Perform vector addition
vector_sum <- vector1 + vector2
cat("Vector Addition:", "\n")
cat(vector_sum)
# Perform vector subtraction
vector_diff <- vector1 - vector2
cat("\n Vector Subtraction:\n")
cat(vector_diff)
# Perform vector multiplication
scalar<-2
vector_scalar_product <- scalar*vector1
cat("\n Vector Scalar Product:\n")
cat(vector_scalar_product)
# Create matrices
matrix1 <- matrix(c(1, 2, 3, 4), nrow = 2, ncol = 2)
matrix2 <- matrix(c(5, 6, 7, 8), nrow = 2, ncol = 2)
# Perform matrix addition
matrix_sum <- matrix1 + matrix2
cat("\n Matrix Addition:\n")
cat(matrix_sum)
# Perform matrix subtraction
matrix_diff <- matrix1 - matrix2
cat("\n Matrix Subtraction:\n")
cat(matrix_diff)
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
# Perform matrix multiplication
matrix_product <- matrix1 % *%(matrix2)
cat("\n Matrix Multiplication:\n")
cat(matrix_product)
# Calculate matrix determinant
matrix_det <- det(matrix1)
cat("\n Matrix Determinant:\n")
cat(matrix_det)
#Calculate Matrix Transpose
matrix_transpose<-t(matrix1)
cat("\n Matrix Transpose:\n")
cat(matrix_transpose)
# Calculate matrix inverse
matrix_inv <- solve(matrix1)
cat("\n Matrix Inverse:\n")
print(matrix_inv)
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
OUTPUT:
Vector Addition:
579
Vector Subtraction:
-3 -3 -3
Vector Scalar Product:
246
Matrix Addition:
[,1] [,2]
[1,] 6 10
[2,] 8 12
Matrix Subtraction:
[,1] [,2]
[1,] -4 -4
[2,] -4 -4
Matrix Multiplication:
[,1] [,2]
[1,] 23 31
[2,] 34 46
Matrix Determinant:
[1] -2
Matrix Transpose:
[,1] [,2]
[1,] 1 2
[2,] 3 4
Matrix Inverse:
[,1] [,2]
[1,] -2 1.5
[2,] 1 -0.5
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
8. Write a R program for any visual representation of an object with creating graphs using
graphic functions: Plot(), Hist(), Linechart(), Pie(), Boxplot(), Scatter plots().
# Creating a vector of data
data <- c(10, 15, 20, 25, 30, 35, 40, 45, 50)
# Plotting a line chart
plot(data, type = "l", main = "Line Chart", xlab = "X-axis", ylab = "Y-axis")
# Creating a histogram
hist(data, main = "Histogram", xlab = "Values", ylab = "Frequency")
# Creating a pie chart
categories<-c("A", "B", "C")
values<-c(30, 40, 50)
pie(values, labels=categories, main = "Pie Chart", col=c("red", "green","blue"))
# Creating a boxplot
data<-list(A=c(2, 4, 6, 8), B=c(1, 3, 5, 7))
boxplot(data, main = "Boxplot", xlab="Groups", ylab = "Values")
# Creating a scatter plot
x <- c(1, 2, 3, 4, 5)
y <- c(10, 20, 30, 20, 50)
plot(x, y, pch=19, col="blue", main = "Scatter Plot", xlab = "X-axis", ylab ="Y-axis")
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
OUTPUT:
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
9. Write an R program for with any dataset containing data frame objects, indexing
and sub-setting data frames and employ manipulating and analyzing data.
#Create a sample employee dataset as a data frame
emp_data<-data.frame(EmployeeId=c(1,2,3,4,5),
FirstName=c("Jhon","Alice","Bob","Carol","David"),
LastName=c("Smith","Johnson","Johnson","Smith","Davis"),
Age=c(30,25,28,35,32),
Department=c("HR","Marketing","Finance","HR","IT"),
Salary=c(50000,55000,60000,52000,70000)
)
#Print the entire employee dataset
cat("Employee Data:\n")
print(emp_data)
#Sunset and index the data frame
cat("\nSubset and Indexing:\n")
#Select employees in the HR department
hr_emp<-emp_data[emp_data$Department=="HR",]
cat("HR Employees:\n")
print(hr_emp)
#Select employees aged 30 or older
old_emp<-emp_data[emp_data$Age>=30,]
cat("Employee aged 30 or Older:\n")
print(old_emp)
#Select employees with salary greater than $55000
high_sal_emp<-emp_data[emp_data$Salary>=55000,]
cat("Employee aged 30 or Older:\n")
print(high_sal_emp)
#Manipulate and analyze the data
cat("\nData Manipulation and Analysis:\n")
#Calculate the average salary
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
avg_sal<-mean(emp_data$Salary)
cat("Average Salary:",avg_sal,"\n")
#Calculate the Maximum age
max_age<-max(emp_data$Age)
cat("\nMaximum Age:",max_age,"\n")
#Calculate the no. of employees in each department
dept_count<-table(emp_data$Department)
cat("\nNumber of Employees in each Department")
print(dept_count)
#Calculate the total Payroll for each department
dept_payroll<-tapply(emp_data$Salary, emp_data$Department, sum)
cat("Total Payroll in Each Department:\n")
print(dept_payroll)
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
OUTPUT:
Employee Data:
EmployeeId FirstName LastName Age Department Salary
1 1 Jhon Smith 30 HR 50000
2 2 Alice Johnson 25 Marketing 55000
3 3 Bob Johnson 28 Finance 60000
4 4 Carol Smith 35 HR 52000
5 5 David Davis 32 IT 70000
Subset and Indexing:
HR Employees:
EmployeeId FirstName LastName Age Department Salary
1 1 Jhon Smith 30 HR 50000
4 4 Carol Smith 35 HR 52000
Employee aged 30 or Older:
EmployeeId FirstName LastName Age Department Salary
1 1 Jhon Smith 30 HR 50000
4 4 Carol Smith 35 HR 52000
5 5 David Davis 32 IT 70000
Employee aged 30 or Older:
EmployeeId FirstName LastName Age Department Salary
2 2 Alice Johnson 25 Marketing 55000
3 3 Bob Johnson 28 Finance 60000
5 5 David Davis 32 IT 70000
Data Manipulation and Analysis:
Average Salary: 57400
Maximum Age: 35
Number of Employees in each Department
Finance HR IT Marketing
1 2 1 1
Total Payroll in Each Department:
Finance HR IT Marketing
60000 102000 70000 55000
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
10. Write a program to create any application of Linear Regression in multivariate Context for
predictive purpose.
#Sample dataset: Salary, Years of Experience. Education Level
data<-data.frame(
Salary=c(50000,60000,75000,80000,95000,110000,120000,130000),
Experience=c(1,2,3,4,5,6,7,8),
Education=c(12,14,16,16,18,20,20,22)
)
#Perform multivariate linear regression
model<-lm(Salary~Experience+Education,data=data)
model
#Predict salaries for new data
new_data<-data.frame(Experience=c(9,10),Education=c(22,24))
predicted_salaries<-predict(model,newdata=new_data)
#Print the predicted salaries
cat("Predicted Salaries:\n")
print(predicted_salaries)
OUTPUT:
Predicted Salaries:
1 2
139333.3 152500.0
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
11. Write a r program to take input from the user (name and age) and display the
Values. Also print the version of R installation.
# Function to take input from the user
getUserInput <- function()
name <- readline(prompt = "Enter your name: ")
age <- as.numeric(readline(prompt = "Enter your age: "))
return(list(name = name, age = age))
# Main program
user <- getUserInput()
cat("Your name is", user$name, "and your age is", user$age, "\n")
# Print R version
cat("R version:", R.version.string, "\n")
OUTPUT:
Enter your name: abc
Enter your age: 45
Your name is abc and your age is 45
R version: R version 4.3.3 (2024-02-29 ucrt)
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
PART - B
1. Write a r program to get the details of the objects in memory
name = "Python";
n1 = 10;
n2 = 0.5
nums = c(10, 20, 30, 40, 50, 60)
print(ls())
print("Details of the objects in memory:")
print(ls.str())
OUTPUT:
[1] "n1" "n2" "name" "nums"
[1] "Details of the objects in memory:"
n1 : num 10
n2 : num 0.5
name : chr "Python"
nums : num [1:6] 10 20 30 40 50 60
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
2. Write a R program to create a sequence of numbers from 20 to 50 and find the
mean of numbers from 20 to 60 and sum of numbers from 51 to 91.
print("Sequence of numbers from 20 to 50:")
print(seq(20,50))
print("Mean of numbers from 20 to 60:")
print(mean(20:60))
print("Sum of numbers from 51 to 91:")
print(sum(51:91))
OUTPUT:
[1] "Sequence of numbers from 20 to 50:"
[1] 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
49 50
[1] "Mean of numbers from 20 to 60:"
[1] 40
[1] "Sum of numbers from 51 to 91:"
[1] 2911
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
3. Write a r program to create a vector which contains 10 random integer values
between -50 and +50.
v = sample(-50:50, 10, replace=TRUE)
print("Content of the vector:")
print("10 random integer values between -50 and +50:")
print(v)
OUTPUT:
[1] "Content of the vector:"
[1] "10 random integer values between -50 and +50:"
[1] 31 -49 49 -38 27 28 -22 -30 -15 17
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
4. Write a R program to get the first 10 fibonacci numbers.
Fibonacci <- numeric(10)
Fibonacci[1] <- Fibonacci[2] <- 1
for (i in 3:10) Fibonacci[i] <- Fibonacci[i - 2] + Fibonacci[i - 1]
print("First 10 Fibonacci numbers:")
print(Fibonacci)
OUTPUT:
[1] "First 10 Fibonacci numbers:"
[1] 1 1 2 3 5 8 13 21 34 55
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
5. Write a r program to get all prime numbers up to a given number (based on the
sieve of eratosthenes).
(Sure, here's an R program to generate all prime numbers up to a given number using the Sieve
of Eratosthenes algorithm )
# Function to generate all prime numbers up to a given number using Sieve of Eratosthenes
sieve_of_eratosthenes <- function(n) {
primes <- rep(TRUE, n)
primes[1] <- FALSE # 1 is not a prime number
# Iterate over numbers starting from 2 up to sqrt(n)
for (i in 2:sqrt(n)) {
# If i is a prime number
if (primes[i]) {
# Mark all multiples of i as not prime
primes[i * i:n] <- FALSE
}
}
# Return prime numbers up to n
return(which(primes))
}
# Get all prime numbers up to a given number (e.g., 50)
n <- 50
all_primes <- sieve_of_eratosthenes(n)
# Print the prime numbers
print(all_primes)
OUTPUT:
[1] 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
6.Write a R program to print the numbers from 1 to 100 and print "fizz" for multiples
of 3, print "buzz" for multiples of 5, and print "fizz buzz" for multiples of both.
for (i in 1:100) {
if (i %% 3 == 0 && i %% 5 == 0) {
print("fizz buzz")
} else if (i %% 3 == 0) {
print("fizz")
} else if (i %% 5 == 0) {
print("buzz")
} else {
print(i)
}
}
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
OUTPUT:
[1] 1 [1] 31 [1] 61 [1] 91
[1] 2 [1] 32 [1] 62 [1] 92
[1] "fizz" [1] "fizz" [1] "fizz" [1] "fizz"
[1] 4 [1] 34 [1] 64 [1] 94
[1] "buzz" [1] "buzz" [1] "buzz" [1] "buzz"
[1] "fizz" [1] "fizz" [1] "fizz" [1] "fizz"
[1] 7 [1] 37 [1] 67 [1] 97
[1] 8 [1] 38 [1] 68 [1] 98
[1] "fizz" [1] "fizz" [1] "fizz" [1] "fizz"
[1] "buzz" [1] "buzz" [1] "buzz" [1] "buzz"
[1] 11 [1] 41 [1] 71
[1] "fizz" [1] "fizz" [1] "fizz"
[1] 13 [1] 43 [1] 73
[1] 14 [1] 44 [1] 74
[1] "fizz buzz" [1] "fizz buzz" [1] "fizz buzz"
[1] 16 [1] 46 [1] 76
[1] 17 [1] 47 [1] 77
[1] "fizz" [1] "fizz" [1] "fizz"
[1] 19 [1] 49 [1] 79
[1] "buzz" [1] "buzz" [1] "buzz"
[1] "fizz" [1] "fizz" [1] "fizz"
[1] 22 [1] 52 [1] 82
[1] 23 [1] 53 [1] 83
[1] "fizz" [1] "fizz" [1] "fizz"
[1] "buzz" [1] "buzz" [1] "buzz"
[1] 26 [1] 56 [1] 86
[1] "fizz" [1] "fizz" [1] "fizz"
[1] 28 [1] 58 [1] 88
[1] 29 [1] 59 [1] 89
[1] "fizz buzz" [1] "fizz buzz" [1] "fizz buzz"
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
7. Write a R program to extract first 10 English letter in lower case and last 10 letters in upper
Case and extract letters between 22nd to 24th letters in upper case.
# Extract first 10 English letters in lower case
first_10_lower <- letters[1:10]
# Extract last 10 letters in upper case
last_10_upper <- toupper(letters[17:26])
# Extract letters between 22nd to 24th letters in upper case
middle_upper <- toupper(letters[22:24])
# Print the results
cat("First 10 English letters in lower case:", first_10_lower, "\n")
cat("Last 10 letters in upper case:", last_10_upper, "\n")
cat("Letters between 22nd to 24th in upper case:", middle_upper, "\n")
OUTPUT:
First 10 English letters in lower case: a b c d e f g h i j
Last 10 letters in upper case: Q R S T U V W X Y Z
Letters between 22nd to 24th in upper case: V W X
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
8. Write a R program to find the factors of a given number.
print_factors = function(n) {
print(paste("The factors of",n,"are:"))
for(i in 1:n) {
if((n %% i) == 0) {
print(i)
}
}
}
print_factors(4)
print_factors(7)
print_factors(12)
OUTPUT:
[1] "The factors of 4 are:"
[1] 1
[1] 2
[1] 4
[1] "The factors of 7 are:"
[1] 1
[1] 7
[1] "The factors of 12 are:"
[1] 1
[1] 2
[1] 3
[1] 4
[1] 6
[1] 12
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
9. Write a R program to find the maximum and the minimum value of a given vector.
nums = c(10, 20, 30, 40, 50, 60)
print('Original vector:')
print(nums)
print(paste("Maximum value of the said vector:",max(nums)))
print(paste("Minimum value of the said vector:",min(nums)))
OUTPUT:
[1] "Original vector:"
[1] 10 20 30 40 50 60
[1] "Maximum value of the said vector: 60"
[1] "Minimum value of the said vector: 10"
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
10. Write a R program to get the unique elements of a given string and unique numbers of
vector.
# Function to get unique elements of a string
get_unique_characters <- function(string) {
unique_chars <- unique(strsplit(string, "")[[1]])
return(unique_chars)
# Function to get unique numbers of a vector
get_unique_numbers <- function(vector) {
unique_nums <- unique(vector)
return(unique_nums)
# Example string
my_string <- "hello world"
# Example vector
my_vector <- c(1, 2, 3, 4, 5, 3, 2, 1)
# Get unique elements of the string
unique_chars <- get_unique_characters(my_string)
# Get unique numbers of the vector
unique_nums <- get_unique_numbers(my_vector)
# Print results
cat("Unique characters of the string:", unique_chars, "\n")
cat("Unique numbers of the vector:", unique_nums, "\n")
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
OUTPUT:
Unique characters of the string: h e l o w r d
Unique numbers of the vector: 1 2 3 4 5
GOVERNMENT FIRST GRADE COLLEGE AURAD
DEPARTMENT OF COMPUTER SCIENCE
STATISTICAL COMPUTING AND R PROGRAMMING
11. Write a r program to create three vectors a,b,c with 3 integers. Combine the three
Vectors to become a 3x3 matrix where each column represents a vector. Print the
Content of the matrix.
# Create vectors a, b, and c with 3 integers each
a <- c(1, 2, 3)
b <- c(4, 5, 6)
c <- c(7, 8, 9)
# Combine the vectors into a 3x3 matrix
matrix_combined <- cbind(a, b, c)
# Print the content of the matrix
print(matrix_combined)
OUTPUT:
abc
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9