Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

R Lab Programs-1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

LAB PROGRAM - 1

Write a R program to find the factorial of a number

> num <- as.integer(readline(prompt="Enter the number of terms to


be printed: "))
if(num<= 0){
print("Invalid input")
}else if(num == 1){
print("Fibonacci series: 0")
}else if(num == 2){
print("Fibonacci series: 0, 1")
}else{
fib_seq <- c(0,1)
for(i in 3:num){
next_num <- fib_seq[i-1]+fib_seq[i-2]
fib_seq <- c(fib_seq,next_num)
}
cat("Fibonacci Sequence: ", fib_seq)
}
OUTPUT:
Enter the number of terms in fib_seq : 6
Fibonacci Sequence : 0 1 1 2 3 5
LAB PROGRAM- 2
Write a R program to find the roots of the Quadratic Equation

quad <-function(a, b, c)
{
disc <- b*b - 4*a*c
if(disc == 0){
print("Roots are equal and real.")
root1 <- -b %/% (2*a);
print(paste("Root:",root1));
}else if(disc > 0){
print("Roots are real and distinct.");
root1 <- (-b + sqrt(disc))%/%(2*a);
root2 <- (-b - sqrt(disc))%/%(2*a);
print(paste("Root 1:",root1));
print(paste("Root 2:%.",root2));
}else{
print("Roots are complex numbers.");
real <- - b/(2*a);
imag <- sqrt(- disc )%/%(2*a);
print(paste("Root 1:",real,"+i",imag));
print(paste("Root 2:",real,"-i",imag));
}
}
a<-as.integer(readline(prompt="Enter coefficient of a: "))
b<-as.integer(readline(prompt="Enter coefficient of b: "))
c<-as.integer(readline(prompt="Enter coefficient of c: "))
if(a == 0 && b == 0){
print("Invalid input.")
}else{
quad(a, b, c)
}

OUTPUT

Enter coefficient of a: 1
Enter coefficient of b: 2
Enter coefficient of c: 1
[1] "Roots are equal and real."
[1] "Root: -1"

Enter coefficient of a: -1
Enter coefficient of b: 4
Enter coefficient of c: 3
[1] "Roots are real and distinct."
[1] "Root 1: -1"
[1] "Root 2:%. 4"
Enter coefficient of a: 12
Enter coefficient of b: 6
Enter coefficient of c: 8
[1] "Roots are complex numbers."
[1] "Root 1: -0.25 +i 0"
[1] "Root 2: -0.25 -i 0”
LAB PROGRAM – 3
Write a R program that use a loop to find the minimum of a vector
X, without using any predefined functions, like min(), sort (), etc

findmin <- function(x){


if(length(x) == 0){
print("Error: Empty vector!")
return(NA)
}
x.min <- x[1]
for(i in 2:length(x)){
if(x[i] < x.min){
x.min <- x[i]
}
}
return(x.min)
}

vector <- c(7, 2, 9, 4, 1, 6)


minterm <- findmin(vector)
print(paste("Minimum value:",minterm))

OUTPUT:
“Minimum value:1”
LAB PROGRAM - 4
Write a R program that generates a random number between 1 and
10/n and prompts the user to get the number. If the user guess is
too high then the program should print too high. If the users guess
is too low then the program should print too low. If the users guess
is correct then print CONGRATULATIONS

random_number <- sample(1:10,1)


guess <- as.integer(readline("Guess a number 1 and 10:"))
while(guess != random_number){
if(guess > random_number){
print("Too High")
}else{
print("Too Low")
}
guess <- as.integer(readline("Guess again"))
}
print("CONGRATULATIONS")

OUTPUT:
Guess a number 1 and 10:5
[1] "Too Low"
Guess again6
[1] "Too Low"
Guess again7
[1] "Too Low"
Guess again9
[1] "CONGRATULATIONS"
LAB PROGRAM -5
Write a program that prompts a user to enter a sentence and count
the number of vowels and consonants using a for loop and if loop
only
countvowelsAndconsonants <- function(text){
text <- tolower(text)

vowels <- c("a","e","i","o","u")


vowel_count =0
consonant_count =0

for(char in strsplit(text,"")[[1]]){
if(char %in% vowels){
vowel_count <- vowel_count+1
}else if (char >= "a"&& char <="z"){
consonant_count <- consonant_count+1
}
}

cat("Number of vowels:",vowel_count,"\n")
cat("Number of consonants:", consonant_count,"\n")
}
#prompt the user to enter a word or a sentence
text <- readline(prompt = "Enter a sentence:")
#call the function to count vowels and consonants
countvowelsAndconsonants(text)

OUTPUT:
Enter a sentence: hi im apoorva
Number of vowels: 6
Number of consonants: 5

Enter a sentence: this is r programming class


Number of vowels: 6
Number of consonants: 17

Enter a sentence: aprajita


Number of vowels: 4
Number of consonants: 4
LAB PROGRAM 6
Write a program in R that creates data frame with two columns, list
of names and a list of corresponding ages. Use the apply family of
function to calculate the mean and median of age of all the people
in the data frame

#create a data frame with names and ages


names <- c("Akhil","Nitish","Anshul","Scientist","Teacher")
ages <- c(20,21,35,38,45)
df <- data.frame(Names=names, Age=ages)
#calculate the mean age using apply family of functions
mean_age <- mean(df$Age)
print(mean_age)

#calculate median
median_age <- median(df$Age)
print(median_age)

OUTPUT:
31.8
35
LAB PROGRAM-7
Write a program in R that defines multiple functions (different
functions )that takes data frames as arguments and returns, mean,
median ,standard deviation respectively, of a specified column. Call
the function with a data frame that contains at least one column
with numeric values.

calculate_mean <- function(column) {


return(mean(column, na.rm = TRUE))
}

# Function to calculate median


calculate_median <- function(column) {
return(median(column, na.rm = TRUE))
}

# Function to calculate variance


calculate_variance <- function(column) {
return(var(column, na.rm = TRUE))
}

# Function to calculate standard deviation


calculate_std_dev <- function(column) {
return(sd(column, na.rm = TRUE))
}
# Function to calculate standard error
calculate_std_error <- function(column) {
return(sd(column, na.rm = TRUE) / sqrt(length(column)))
}

# Function to calculate statistics for a single column


calculate_column_stats <- function(column) {
stats <- c(
mean = calculate_mean(column),
median = calculate_median(column),
variance = calculate_variance(column),
std_dev = calculate_std_dev(column),
std_error = calculate_std_error(column)
)
return(stats)
}

# Create a sample dataframe


data <- data.frame(
name = c("Alice", "Bob", "Charlie", "David", "Emma"),
age = c(25, 32, 45, 28, 22),
income = c(50000, 60000, 75000, 55000, 40000),
expenses = c(30000, 35000, 40000, 32000, 28000)
)

# Numeric columns
numeric_columns <- sapply(data, is.numeric)

# Use lapply to calculate statistics for each numeric column


numeric_stats <- lapply(data[, numeric_columns],
calculate_column_stats)

# Convert the list of statistics into a data frame


numeric_stats_df <- do.call(rbind, numeric_stats)
rownames(numeric_stats_df) <- paste0("Numeric_",
colnames(data)[numeric_columns])

# Print numeric statistics


print("Numeric Column Statistics:")
print(numeric_stats_df)

OUTPUT:
"Numeric Column Statistics:"
mean median variance std_dev std_error
Numeric_age 30.4 28 8.030e+01 8.961027 4.007493
Numeric_income 56000.0 55000 1.675e+08 12942.179106 5787.91
8451
Numeric_expenses 33000.0 32000 2.200e+07 4690.415760 2097.61
76
LAB PROGRAM 8
Write a program in r that reads a list of numbers from a file and
replaces any negative values with 0. Use apply familiar functions
and calculate the mean, variance and sd of each column in the data
frame
original_data <- read.table("C:/Users/apoor/Downloads/data2.txt",
header = TRUE)

# Display the original data


cat("Original Data:\n")
print(original_data)

# Replace negative values with zero using apply


modified_data <- data.frame(apply(original_data, 2,
function(column) ifelse(column < 0, 0, column)))

# Call the function to display data modification


cat("\nData after replacing negative values with zero:\n")
print(modified_data)

# Function to calculate mean, variance, and standard deviation


calculate_stats <- function(column) {
stats <- c(
mean = mean(column),
variance = var(column),
std_dev = sd(column)
)
return(stats)
}

# Use apply to calculate statistics for each column


column_orig_stats <- lapply(original_data, calculate_stats)

OUTPUT:
Original Data:
col1 col2 col3
1 3 -2 7
2 -1 5 8
3 4 2 -6
4 -3 0 9
5 6 -4 12
6 2 -7 10
7 9 8 -5
8 -2 11 14
9 -8 6 3
10 7 0 -9

Data after replacing negative values with zero:


col1 col2 col3
1 3 0 7
2 0 5 8
3 4 2 0
4 0 0 9
5 6 0 12
6 2 0 10
7 9 8 0
8 0 11 14
9 0 6 3
10 7 0 0
>
LAB PROGRAM-9
Write a program in r that defines a class student with name age
and height as list values. Define multiple functions or multiple
methods that takes the class list values as arguments and returns
and name in uppercase, the mean median sd, variance, and error
rate of age and height values display the results

Student <- setClass(


"Student",
slots = c(
name = "character",
age = "numeric",
height = "numeric"
)
)

# Create an instance of the Student class


student1 <- new("Student", name = "Alice", age = 21, height = 165)
student2 <- new("Student", name = "Bob", age = 22, height = 178)
student3 <- new("Student", name = "Charlie", age = 21, height = 172)
student4 <- new("Student", name = "David", age = 19, height = 160)
student5 <- new("Student", name = "Emma", age = 23, height = 175)
student6 <- new("Student", name = "Frank", age = 28, height = 170)
student7 <- new("Student", name = "Grace", age = 34, height = 163)
student8 <- new("Student", name = "Henry", age = 20, height = 180)
student9 <- new("Student", name = "Ivy", age = 27, height = 168)
student10 <- new("Student", name = "Jack", age = 30, height = 175)

# Define functions to operate on Student objects


get_name_uppercase <- function(student) {
return(toupper(student@name))
}

get_stats <- function(student) {


age <- student@age
height <- student@height

stats <- list(


mean_age = mean(age),
median_age = median(age),
mean_height = mean(height),
median_height = median(height)
)

return(stats)
}

# Create lists to store results for each metric


names_upper <- character()
mean_ages <- numeric()
median_ages <- numeric()
mean_heights <- numeric()
median_heights <- numeric()

# Call functions for each student and populate the result lists
students <- list(student1, student2, student3, student4, student5,
student6, student7, student8, student9, student10)

for (student in students) {


names_upper <- c(names_upper, get_name_uppercase(student))
stats <- get_stats(student)

mean_ages <- c(mean_ages, stats$mean_age)


median_ages <- c(median_ages, stats$median_age)
mean_heights <- c(mean_heights, stats$mean_height)
median_heights <- c(median_heights, stats$median_height)
}

# Create a data frame to display the separate results


results <- data.frame(
Names = names_upper
)
# Display the results
print(results)
print(paste("Mean Age: ", mean(mean_ages)))
print(paste("Median Age: ", median(median_ages)))
print(paste("Mean Height: ", mean(mean_heights)))
print(paste("Median Height: ", median(median_heights)))

OUTPUT

Names
1 ALICE
2 BOB
3 CHARLIE
4 DAVID
5 EMMA
6 FRANK
7 GRACE
8 HENRY
9 IVY
10 JACK
[1] "Mean Age: 24.5"
[1] "Median Age: 22.5"
[1] "Mean Height: 170.6"
[1] "Median Height: 171"
LAB PROGRAM- 10
Write a program in R to create student records, create an S3 class
Student Record for objects that are a list with a named elements
‘name’ ‘Subject completed’ ‘grades’ ‘credit’. Write a student record
method for the generic function mean, which return weighted gpa,
with subjects weighted by credit also write a student record
method for print, which employs formatting and arranging subjects
by year code. Create another class for a cohort of students and
write methods for mean and print the mean for every student in
the cohort.

studentRecord <- list(


name = NULL,
subjects_completed = NULL,
grades = NULL,
credit = NULL
)

# Create the mean method for studentRecord


mean.studentRecord <- function(x, ...) {
total_credits <- sum(x$credit)
weighted_grades <- sum(x$grades * x$credit)
mean_gpa <- weighted_grades / total_credits

return(mean_gpa)
}
# Create the print method for studentRecord
print.studentRecord <- function(x, ...) {
cat("Name:", x$name, "\n")
cat("Subjects Completed:", x$subjects_completed, "\n")
cat("Grades:", x$grades, "\n")
cat("Credit:", x$credit, "\n")
}

# Create the cohort class


cohort <- list(
students = NULL
)

# Create the mean method for cohort


mean.cohort <- function(x, ...) {
student_gpas <- sapply(x$students, mean)
mean_gpa <- mean(student_gpas)

return(mean_gpa)
}

# Create the print method for cohort


print.cohort <- function(x, ...) {
for (student in x$students) {
print(student)
cat("---------------------------\n")
}
}

# Create a sample student record


student <- studentRecord
student$name <- "John Doe"
student$subjects_completed <- c("Math", "English", "Science")
student$grades <- c(80, 90, 85)
student$credit <- c(3, 4, 3)

# Calculate the mean GPA for the student


mean_gpa <- mean(student)
cat("Mean GPA:", mean_gpa, "\n")

# Print the student record


print(student)

# Create a sample cohort


cohort <- cohort
cohort$students <- list(student, student)
# Calculate the mean GPA for the cohort
mean_gpa_cohort <- mean(cohort)
cat("Mean GPA for Cohort:", mean_gpa_cohort, "\n")

# Print the student records in the cohort


print(cohort)

OUTPUT:

Mean GPA: NA
$name
[1] "John Doe"

$subjects_completed
[1] "Math" "English" "Science"

$grades
[1] 80 90 85

$credit
[1] 3 4 3

Mean GPA for Cohort: NA


$students
$students[[1]]
$students[[1]]$name
[1] "John Doe"

$students[[1]]$subjects_completed
[1] "Math" "English" "Science"
$students[[1]]$grades
[1] 80 90 85

$students[[1]]$credit
[1] 3 4 3

$students[[2]]
$students[[2]]$name
[1] "John Doe"

$students[[2]]$subjects_completed
[1] "Math" "English" "Science"

$students[[2]]$grades
[1] 80 90 85

$students[[2]]$credit
[1] 3 4 3

You might also like