STATISTCAL COMPUTING ANDR PROGRAMMING MANNUAL
1. Write a R program Take the input_from the user include_name.age,class,section.register
number,phone_number,address.
Definition:
> To readline () function is used read the line
> as.integer () is used to convert the character to number
Source code:
my.name <-readiine(prompt="Enter the name: ")
my.age <-readline(prompt="Enter the age: ")
#comert character into integer
my.age <-as.integer(my.age)
# Take user input for chiss
class <-readline("Enter your class: ")
# Take user input for course
class <- readline("Enter your course: ")
# Take user input for section
section <- readiine("Enter_your section: *)
# Take user input for register. number
register_number <-readiine("Enter your register number: ")
# Take user input for phone number
phone_number <- readline("Enter your phone number: ")
t
# Take user input for address
address <- readline("Enter your address: ")
# Display the collected information
")
prin(paste("Hi", my.name, "next year you will be", my.age+1, "years old.”))
cat("Class:", class, "\n")
cat("Section:", section, "\n")
cat("Register Number’, register_number, "\n)
cat("\nUser Information:cat("Phone Number:', phone_number, "\n')
cat("Address:", address, "\n")
Output:
Enter the name: SANDYA
Enter the age: 24
Enter your class: 3rd BC A
Enter your course: Bachelor of Application
Enter your section: A
Enter your register number: U01BE20456
Enter your phone number: 9586741236
Enter your address: #345 2nd Main,3rd Cross J P Nagara Mysuru
User, Information:
[1] "Hi SANDYA next year you will be 25 years old."
Class: Bachelor of Application
Section: A
Register Number: U01BE20456
Phone Number: 9586741236
Address: #345 2nd Main, 3rd Cross J P Nagara Mysuru
2.To Display the multiplication _of the table to take the input from the user and directly given to
num = as.integer(readline(prompt = "Enter a number: "))
# use for loop to iterate 10 times
for(i in 1:12) {
prin(paste(num,'x’, i,
}
num*i))
mum = 6
for(i in 1:12) (
print(paste(num,'x’, i,
’, num*i))
num = 12
fori in 1:12) {
print(paste(numx’,
)
OUTPUT:U1] "2 x5=10"
(1) '2x6=12"
ty '2x7
UJ 2x8
[1] "2x9 = 18"
[1 "6x11
("12x1
(1) "12 x2
[1] "12 x3=36"
[1] "12 x4=48"
[1] "12 x5=60"
[1] "12 x6=72"
U1) "12 x7=384"
[1] "12 x8=96"
[1] "12 x 9= 108"
[1] "12 x 10= 120"
UJ "12 x 11 = 132"
[1] "12 x 12 = 144"3.Write aR program To find out sumofnatural numbers.
Definition of Natural numbers:
Natural numbers area part of the number system inching all the positive numbers from 1 to
infinity
Formula for calculate the sum:
Sumen(n+1)/2
Source code:
num =asinteger{readline(prompt = "Enter a number: "))
iftoum <0) (
prit("Enter a postive number")
Jebe (
sum = (num. * (num + 1)) / 2;
ptint(paste("The sum é", sum)
}
Output:
Enter anumber: 5
[1] "The sum is 15"
3.Write aR program To find the largest of three numbers
Definition: The largest element_of a number is the
number with the highest_numerical_value_of the
three numbers,
Source code:
# Function to ind the knpst of three numbers
find_largest <- funetion(a, b,c) {
if @>=b && a>=o) {
return(a)
J ebe if (b >=a && b>=c) {
retumn(b)
}ebe {
return(c)
}# Input three numbers
num <- as.numeric(readline("Enter the first number: "))
num2_<- as.numerie(readline("Enter the second number: "))
num3 <-as.numeric(readline("Enter the third number: "))
gest < finc_largest(numl, mum2, nun3)
ccat("The largest number among’, numl, ",", num2, ", and", num3, "is", largest, "\n')
Output:
Enter the first number: 65
Enter the second number:
45Enter the third
number: 78
‘The largest number among 65,45, and 78 is 78
5.Write a R program To check given number is Prime number or not
Definition of prime number: Number in which is divisible by I and itself is called prime
‘number.
Ex1,3,5,7.11,13,17,23,29..
Source code:
num=as.integer(readline(prompt="Enter a numb
flag =0
iffoum > 1) {
# check for factorsflag = 1
ford in 2(num-1)) {
if (um %% i) == 0) (flag =0
breakprnt(paste(num,"is a prime matber"))
Jebe {
Prin(paste(num,"is not a prime nurber’))
}
Output:
Enter anumber: 12
[1] '"12is not aprime number"
Enter anumber: 5
[1] "Sis a prime number”
6.Write a R program To create calculator.
Definition:
To perform basic calculations and use various mathematical functions directly in the R consol: or
in your R script. Here are some common calculator-like operations and functions in R:
1 Basic Arithmetic Operations:
+ Addition: +
+ Subtraction: ~
+ Mutiplication: *
+ Division: /
+ Exponentiation:
Source code
+# Function to perform addition
add <- function(a, b) {
return(a +b)
}
#Funetion to perform subtraction
subtract <- fimetion(a, b) {
retum(a -b)
}
+# Function toperform mukipfcation
muiply <- function(a, b) {
retum(a *b)}
# Furetion to perform division
divide < function(a, b) {
(b==0){
retun("Division by zero is not allowed,
}ebe {
retur(a /b)
}
}
# Main calculator loop
while (TRUE) (
cat(’Simple Caleulatorin’)
cat("I. Addition\n")
ccat("2.. Subtraction\n")
cat("3. Multplication\n")
cat("4. Division\n")
cat("5. Quit\n")
choice <-as.integer(readline("Enter your choice (1-5;
if (choice ==5) {
cat("Exiting the calculator. Goodbye to everyone!\n’)
break
}
if (choice <1 || choice >5){
cai(Invalid chove, Pkase enter a valid option.\n")
next
}
num <- as.numeric(readline("Enter the first number: "))
num? <-as.numeric(readline("Enter the second number: "))result <- switeh(
choice,
"Y" =add(numl, num2),
subtract(numl, num2),
"3" = multiply(num1, num2),
"4" =divide(numl, rund)
)
cat(‘Result: ", resuit, yin")
}
Output: Simple Calculator
1. Addition
2. Subtraction:
3. Mutiplication
4. Division
5. Quit
Enter your choice (1-5): 1
Enter the first. number: 25
Enter the second number: 24
Result: 49
Simple Calculator
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Quit
Enter your choice (1-5): 2
Enter the first_ number: 25
Enter the second number: 24
Result: 1
Simple Calculator
1. Addition
2. Subtraction
3. Muttiplication
4. Division
5. Quit
Enter your choice (1-5):3
Enter the first number: 26
Enter the second number: 2
Result: 523
Simple Calculator
1. Addition
Enter your choice (I~
Enter the first number: 12
Enter the second number:
Result: 4
Simple Calculator
1. Addition
3. Multiplication
4. Division
Enter your choice (1-5):5
Exiting. the calcutor. Goodbye to everyone!
3. Multiplication
5. Quit
4. Division
2. Subtraction
5S. Quit
2. Subtraction7..Write a R program to check given number is evenor odd number.
Definition : An even number is a whole number that is divisible by 2 without leaving_a remainder.
In other words, when you divide an even number by 2, the result is a whole number,
Even numbers are typically expressed as 2n, where “nis an integer,
Examples of even numbers include:
246810
Odd number: an odd number _is a whole number that is_not divisible by 2 without leaving a
remainder. When you divide_an odd number by 2, you will_have a remainder_of 1
Odd numbers_are often expressed_as 2n + 1, where ‘n'' is an integer.
Exampks of odd numbers include: 13579
Source code:
#Function to check if a number is oddoreven
check_odd_even <- function(number) {
if (number %% 2 == 0) (
return("Even")
Jele {
return("Odd")
# Input number to check
input_number b
less_than_or_equal_to <-
# Miscellaneous operators
modulus <-a%% b
exponentiation <- a2
cat("Relational operators:\n")
cat(paste("a >", greater_than, "\n'))
cat(paste("a <= b:", less_than_or_equal_to, "\n"))i
cat("\nMiscellaneous operators\n")
ccat(paste("a 9% b (modulus):", modulus, "\n"))
ccat(paste("a"2 (exponentiation):", exponentiation, "\n"))
# Control Structures with ‘else if” ladder
if (greater_than) {
cat(‘a is greater than b\n")
) ese if (!greater_than) {
cat("a is not greater than b\n")
} else {
cat("a and b are equalin")
}
# Repeat loop
x<55
repeat {
cat(paste("Value of x", x, "wn'))
x57){
break
}
}
# Default values for arguments
add_numbers <- function(x, y = 10) {
xty
}result <-add_numbers(5) #y takes its default value (10)
resul <- add_numbers(5, 20) # y is provided as 20
cat("\nDefault values for arguments:\n")
cat(paste("add_numbers(5):", resultl, "\n"))
cat(paste("add_numbers(5, 20):", result2, "\n"))
# Create a complex object using a list
person < list(
name = "John",
age = 30,
address = list
steet = "K T STREET",
city = "MYSURU",
zip = "571104"
a
hobbies = c("Reading", "Hiking", "Cooking")
)
# Access and display the complex object
‘Name: ", person$name, "\n’,"Age: ", personSage, "\n")
: ", personSaddress$street, "\n","City: ", personSaddressScity,
", personSaddress$zip, "\n")
:", paste(personShobbies, collapse =
Enter the First Number’S
Enter the Second Number
Relational operators:
Miscellaneous operators:
4.%% b (modulus): 1a°2 (exponentiation): 25
ais greater than b
Value of x: 55
Value of x: 56
Value of x: 57
Default values for arguments:
add_numbers(5): 15
add_numbers(5, 20): 25
Street: KT STREET
City: MYSURU
Zip: 571104
Hobbies: Reading, Hiking, Cooking
15.Write a R program to implement_area of circle, rectangle using $3 S4and S5
(reference class).
DEFINITION:
S3 Class:Syntax
class name <: lst(classname,classmembers)
class name [Object / create object name
S4 class: Syntax
setClass ("name of the class", member variable)
objectnameLinew(classname, value of the member variable)
Objectname
SS class:Syntax
ClassnameCisetRefClass(name of the class,member variable)
objectname<-classname(name of the class,value of the member)
objectnameSS ae Oro ee Sea TELS
Be aa elma Reco
Lory
* Formula: Area = length
width
eRe Ur Reet
the rectangle.
3. Triangl
Formula (for a triangle with base b
EUR a.) ee ae
base x height
SOURCE CoD!
# Define functions to calculate area of circle, rectangle, and triangle using S3 method
circle_area <- function(radius) (
return(pi * radius*2)
}
radius <- 5
cirele_area_s3 <- circle_area(radius)
cat("Area of Circle ($3):", circle_area_s
# Define S4class for Rectangle
setClass(’Rectangke", representation(length = "numeric", width = “numeric"))
# Define methods to calculate area for circle and rectangle
setGeneric(“area", function(object) standardGeneric("area"))
setMethod(“area", "Rectangle", finction(object) object@kngth * object @ width)
# Usage
rectangl2 <-new("Rectangle”, length = 4, width = 6)cat("Area of rectangk(s4):"area(rectangle2)) # Calculate area of rectangle
Triangle <- setRefClass(
“Triangle”,
fields = list(base = "numeric", height = “numeric"),
methods = list(
calculate_area = function() {
retum(0,5 * base * height)
1
)
)
# Create objects of Circle, Rectangle, and Triangle classes
triangle <- TriangkSnew(base = 3, height = 8)
triangle_area_s5_<- triangleScalculate_area()
cat("\n Area of Triangle (S5):", triangle_area_s5, "\n")
oUuTPUT:
Area of Circle: 78.53982
Area of Rectangle: 24
Area of Triangle: 10.5
1
Write a R program To find mean, median,variance.range using functio1
. Mean: It's the average of a set of numbers. You find it by adding up all the values and dividing
by the count of those values. For example, for the numbers 2, 4, 6, 8, the mean is (2+ 4 +6+
8)/4=5.
. Median: It’s the middk value in a dataset when the valves are arranged in ascending or
descending order. If there's an even number of values, the median is the average of the two
middle numbers. For instance, in the set 3, 7, 9, 12, 15, the median is 9. If you have 2, 4, 6, 8,
the median is (4 + 6)/2=5.3. Variance: I's a measure of how spread out the numbers in a dataset are. It tells you the average
of the squared differences from the mean. Larger variance means the data points are more
spread out from the mean. Calculating variance involves finding the difference between each
value and the mean, squaring those differences, adding them up, and then dividing by the count
of values.
4. Range: It's the difference between the highest and lowest values in a dataset. For example, in
the set 2, 4, 6, 8, the range is 8 -2=6.
SOURCE CODE:
# Funetion to calculate mean
calculate_mean <- function(data) {
return(mean(data))
}
# Function to cal
ate median
calculate_median <- function(data) {
return(median(data))
1
# Function to calculate variance
calculate_variance <- function(data) {
return(var(data))
}
+# Function to calculate range
calculate_range <- function(data) {
return(max(data) - min(data))
}
# Example data
dataset <- 6(25, 30, 45, 50, 60, 70, 80, 85, 90, 95)
# Calculate statistics
mean_value < calculate_mean(dataset)median_value <- calculate_median(dataset)
variance_value <- cakculate_variance(dataset)
range_value <- calculate_range(dataset)
# Printing the calculated statistics
cat("
cat("Median:", median_value, "\n")
cat("Variance:’, variance_value, "\n")
jean:", mean_value, "\n"
cat("Range:", range_value, "\n")
OUTPUT: Mean: 63
Median: 65
Variance: 623.3333,
Range: 70
17.Write a R program To implent using Bernoulli,Binomial,Poisson distributions mean
Bernoulli Distribution: A Bernoulli distribution models a random experiment with
‘two possible outcomes, typically labeled as success (usually denoted as 1) and failure
(usually denoted as 0).
+ Mean (n):p
+ Variance (o”): p * (1 - p).
. Binomial Distribution:A binomial distribution represents the number of successes in
a fixed number of independent Bernoulli trials, each with the same probability of
success,
+ Mean (i):n *p,
where nis the number of trials and
pis the probability of success in each trial
«Variance (on * p*(1-p),
Poisson Distribution A Poisson distribution models the number of events occurring
in a fixed interval of time or space when these events occur with a known constant
mean rate and independently of the time since the last event.
+ Mean (1): The mean of a Poisson distribution is A (lambda), which represents
the average rate of occurrence of the event.
+ Variance (6): (lambda).
In a Poisson distribution, both the mean and variance are equal
SOURCE CODE:
i
i
i# Set seed for reproducibility
set.seed(123)
# Function to generate random numbers from Bemoulli_ distribution
gen Ber_Ran_Num <- function(prob, 1) {
retur(rbinom(n, 1, prob))
}
# Function to generate random numbers from Binomial distribution
gen_Bin_Ran_Num <-function(size, prob, n) {
retum(rbinom(n, size, prob))
}
+# Function to generate random numbers from Poisson distribution
gen Pois_Ran_Num <- function(ambda, 1) {
retun(rpois(n, lambda))
}
+# Function to cakulate basic statistics for a given dataset
cakulateStatistics <-fimetion(data) (
return(c(
‘mean = mean(data),
variance = var(data)
»
}
# Set parameters for distributions
prob_bernoulli <- 0.3
size_binomial <- 10
prob_binomial <- 0.5lambda_poisson <-3
sampk_size <- 10
# Generate random numbers from diferent distributions
bernoulli_data <- gen Ber_Ran_Num (prob_bemoull, sample_size)
binomial_data <- gen_Bin_Ran_Num(size_binomial, prob_binomial, sample_size)
poisson_data <- gen_Pois_Ran_Num(lambda_poisson, sample_size)
#Ca
‘ulate statistics for each distribution
stats_bernoulli <- cakculateStatisties(bernoulli_data)
stats_binomial <- calculateStatistics(binomial_data)
stats_poisson <- calculateStatistics(poisson_data)
# Print results
cat("Bemoulli Distribution Statistics:\n")
print(stats_bernoulli)
cat("\nBinomial Distribution Statistics:\n")
print(stats_binomial)
cat("\nPoisson Distribution Statistics:\n")
print(stats_poisson)
ourrut:
Bernoulli Distribution Statistics:
mean variance
0.400000 0.2666667
Binomial Distribution Statistics:
mean variance
5.200000 4.177778
Poisson Distribution Statistics:
mean variance
3.700000 3.5666618.Write a R program for any visual representation of an object with creating graphs
using graphic functions: Plot(),Hist(),Linechart(, Pie(),Boxplot(),Scatterplots().
DEFINITION:
1. Plot(): The plot() function is a general method used to create a plot or a chart. It can generate
different types of plots like line plots, scatter plots, and more, depending on the programming
language or library being used.
2. Hist(): The hist() function is used to create a histogram, which is a graphical representation of,
the distribution of numerical data. It displays the frequencies of different values within
specified ranges.
3. Linechart(): A Linechart( or plot() with lines typically represents data points connected by
straight lines. It's commonly used to disphy trends or changes in data over time or any
continuous variable.
4. Pie(): The pie() fimction generates a pie chart, a circular statistical graphic divided into slices
to illustrate numerical proportions. Each slice represents a proportion of the whole.
5. Boxplot(): The boxplot() function creates a box-and-whisker plot, which displays the
distribution of a dataset along a single axis. It shows the minimum, first quartile, median, third
quartile, and maximum of a set of data.
6. Scatterplots(): The scatterplot() fiction generates a scatter plot, which represents data asa
collection of points on a two-dimensional plane. Each point represents the value of two
different variables.
Source code:
# Generating data for plotting
x< 1:10
yor
# Cre
g apt
plot(x, y, type ="o", col = "blue", main = "Plot of y= x2", xlab = "X-axis", ylab = "Y-axis")
# Creating a histogram
hist(xy, col = "skyblue", main = "Histogram ", xlab = "X-axis", ylab = "Y-axis")# Creating a tine chart
plot(x, y, type = I’, col = "red", main = "Line Chart: y = x42", xlab = "X-axis", ylab = "Y-
axis")
# Creating a pie chart
labels <- c("Category A", "Category B", "Category C”, "Category D")
pie(x, labels = labels, col = rainbow(length(x)), main = "Pie Chart")
# Creating a boxplot
boxplot(y, col = "darkblue", main = "Boxplot")
# Sample data vectors
age <- (5, 6, 7, 8,9) # Ages of children in years
height <- c(3.2, 3.5, 3.6, 3.9, 4.1) # Heights of children in feet
# Creating a scatter plot
plot(age, height, main = "Scatter Plot of Age vs Height",
"Age (years)", ylab = "Height (feet)")
xlab =
OUTPUT:onc
Pie Chart
Category D
Category C
Category B
Category A