PART B my_dict<-list() my_dict ["banana"]<-1 my_dict ["apple"]<- 2 my_dict ["mango"]<-3 print(my_dict["banana"]) if("banana" %in% names(my_dict)){ print("banana is in the dictionary") } if("mango" %in% names(my_dict)){ my_dict<-my_dict[!names(my_dict)=="mango"] } print(my_dict) 2 year = as.integer(readline(prompt="Enter a year: ")) if((year %% 4) == 0) { if((year %% 100) == 0) { if((year %% 400) == 0) { print(paste(year,"is a leap year")) } else { print(paste(year,"is not a leap year")) } } else { print(paste(year,"is a leap year")) } } else { print(paste(year,"is not a leap year")) } 3 df=data.frame(id=c(25,40,30,30), name=c('isaq','owa','puni','rah'), gender=c('m','m','m','m'), marks1=c(99,45,30,NA), marks2=c(89,99,50,60)) df df$id[df$id == 40]<- "45" df df$name[df$name == 'isaq']<- "isaqsa" df df$id[df$id == 30 & df$gender == 'm']<- "67" df df[df == 90]<- "95" df library('data.table') df2=as.data.table(df) df2[id==30, id==40] df2 df = data.frame(id=c(25,30,30,45,40,47), marks1=c(99,45,30,NA,60,55), marks2=c(89,99,50,60,NA,45)) df library(dplyr) d<-mutate(df,id=case_when( id==30 ~40, TRUE~id )) df 4 df<- data.frame(id=c('1','2','3','4'), name=c('is','sa','aq','md'), gender=c('m','m','m','m'), dob= as.Date('2003/12/23','2000/12/22','2000/11/25','2000/9/4'), state =c('NZ','CA','NA','IN'), row.names = c('r1','r2','r3','r4')) df library('dplyr') df%>% select(2,3) df%>% select(2:3) df%>% select(c('name','gender')) df%>% select('name','gender') df%>% select('name':'state') df%>% select(starts_with('gen')) df%>% select(-starts_with('gen')) df%>% select(ends_with('e')) df%>% select(contains('a')) df%>% select_if(is.numeric) 5 df=data.frame(id=c(1,2,3,NA), address=c('orange st','mango st','apple','banana st'), work_address=c('main st','kiwi st','drag st','pine st')) df df$address[df$address == 'orange st']<- 'pink st' df df[df == 'pink st']<-'orange st' df library(stringr) df$address<- str_replace(df$address, "st","street") print(df) df['id'] <- df['id']*5 df df$address[df$address == 'orange street']<- df$work_address df library(dplyr) df<- d%>% mutate(address = ifelse(address ==' ',work_address,address)) df df[is.na(df)]<="" df PART A 1 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)) 4 Write a 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 print("First 10 letters in lower case:") t = head(letters, 10) print(t) print("Last 10 letters in upper case:") t = tail(LETTERS, 10) print(t) print("Letters between 22nd to 24th letters in upper case:") e = tail(LETTERS[22:24]) print(e) 5 Write a program to create three vectors a,b,c with 3 integers. Combine the three vectors to become a 3×3 matrix where each column represents a vector. Print the content of the matrix a<-c(1,2,3) b<-c(4,5,6) c<-c(7,8,9) m<-cbind(a,b,c) print("Content of the said matrix:") print(m) 2 6 Write a program to create a list of random numbers in normal distribution and count occurrences of each value. n = floor(rnorm(1000, 50, 100)) print('List of random numbers in normal distribution:') print(n) t = table(n) print("Count occurrences of each value:") print(t) 7 Write a R program to create a 5 × 4 matrix, 3 × 3 matrix with labels and fill the matrix by rows and 2 × 2 matrix with labels and fill the matrix by columns. m1 = matrix(1:20, nrow=5, ncol=4) print("5 × 4 matrix:") print(m1) cells = c(1,3,5,7,8,9,11,12,14) rnames = c("Row1", "Row2", "Row3") cnames = c("Col1", "Col2", "Col3") m2 = matrix(cells, nrow=3, ncol=3, byrow=TRUE, dimnames=list(rnames, cnames)) print("3 × 3 matrix with labels, filled by rows: ") print(m2) print("3 × 3 matrix with labels, filled by columns: ") m3 = matrix(cells, nrow=3, ncol=3, byrow=FALSE, dimnames=list(rnames, cnames)) print(m3) 9 Write a R program to create a simple bar plot of five subjects marks. marks = c(70, 95, 80, 74) barplot(marks, main = "Comparing marks of 5 subjects", xlab = "Marks", ylab = "Subject", names.arg = c("English", "Science", "Math.", "Hist."), col = "darkred", horiz = FALSE) 4 # R program to illustrate # Creating an object in memory # Numerical object x = 5 print(x) # String object name = "Amiya" print(name) # Vector object vec1 = c(1, 2, 3) print(vec1) vec2 = c("A", "B", "C") print(vec2) # List object listOfNumber = list( "Numbers" = vec1, "Characters" = vec2 ) print(listOfNumber) # Data frame object myDataFrame = data.frame( "Numbers" = vec1, "Characters" = vec2 ) print(myDataFrame) # Listing objects in memory # Numerical object x = 5 print(x) # String object name = "Amiya" print(name) # Vector object vec1 = c(1, 2, 3) print(vec1) vec2 = c("A", "B", "C") print(vec2) # List object listOfNumber = list( "Numbers" = vec1, "Characters" = vec2 ) print(listOfNumber) # Data frame object myDataFrame = data.frame( "Numbers" = vec1, "Characters" = vec2 ) print(myDataFrame) # Listing objects using object() cat("Using object()\n") print(objects()) # Listing objects using ls() cat("Using ls()\n") print(ls()) # R program to illustrate # Deleting objects in memory # Numerical object x = 5 print(x) # String object name = "Amiya" print(name) # Vector object vec1 = c(1, 2, 3) print(vec1) vec2 = c("A", "B", "C") print(vec2) # List object listOfNumber = list( "Numbers" = vec1, "Characters" = vec2 ) print(listOfNumber) # Data frame object myDataFrame = data.frame( "Numbers" = vec1, "Characters" = vec2 ) print(myDataFrame) # Deleting all objects using rm() rm(list = ls()) cat("After deleted all objects listing of the object:\n") print(ls()) 4b library(dplyr) # create a data frame d <- data.frame(FirstName=c("Suresh", "Ramesh", "Tanya", "Sujata"), Salary=c(50000, 60000, 70000, 80000), Expenses=c(20000, 15000, 30000, 25000)) print(d) # adding new columns d <- mutate(d, Age=c(25, 28, 22, 27), Savings=Salary - Expenses) print(d) # adding a new column before FirstName d <- mutate(d, Title=c("Mr", "Mr", "Ms", "Ms"), .before=FirstName) print(d) # adding a new column after FirstName d <- mutate(d, LastName=c("Singh", "Pande", "Sinha", "Roy"), .after=FirstName) print(d) 7 EXPERIMENT 7A WRITE A R PROGRAM TO CALCULATE MEAN,MEDIAN,MODE OF STUDENT MARKS AND PLOT HISTOGRAM PLOT USING GGPLOT2 PACKAGE. # Load necessary libraries for plotting library(ggplot2) # Function to calculate modes calculate_modes <- function(data) { freq_table <- table(data) modes <- as.numeric(names(freq_table)[freq_table == max(freq_table)]) return(modes) } # Initialize lists to store student information student_names <- vector("character", length = 3) usn_numbers <- vector("character", length = 3) marks_lists <- list() # Input student information and marks for (i in 1:3) { cat("Enter information for Student", i, "\n") student_names[i] <- readline(prompt = "Student Name: ") usn_numbers[i] <- readline(prompt = "USN No.: ") marks <- numeric(3) for (j in 1:3) { marks[j] <- as.numeric(readline(prompt = paste("Enter Mark", j, ": "))) } marks_lists[[i]] <- marks cat("\n") } # Calculate mean for each student mean_values <- sapply(marks_lists, mean) # Calculate median for each student median_values <- sapply(marks_lists, median) # Calculate modes using the function for each student mode_values <- lapply(marks_lists, calculate_modes) # Create a data frame for plotting plot_data <- data.frame(StudentName = rep(student_names, each = 3), Mark = unlist(marks_lists)) # Print the results and plot histograms for each student for (i in 1:3) { cat("Student Name:", student_names[i], "\n") cat("USN No.:", usn_numbers[i], "\n") cat("Marks:", paste(marks_lists[[i]], collapse = ", "), "\n") cat("Mean:", mean_values[i], "\n") cat("Median:", median_values[i], "\n") if(length(mode_values[[i]]) == 1) { cat("Mode:", mode_values[[i]], "\n") } else { cat("Modes:", paste(mode_values[[i]], collapse = ", "), "\n") } cat("\n") # Plot histogram chart for each student ggplot(subset(plot_data, StudentName == student_names[i]), aes(x = Mark)) + geom_histogram(binwidth = 5, fill = "red", color = "black") + labs(title = paste("Student", student_names[i], "Marks Distribution"), x = "Marks", y = "Frequency") } 7b' EXPERIMENT 7B: Write a R Program to create a Data frames which contain details of 5 employees and display the details # Create empty vectors to store employee details employee_ids <- numeric(0) first_names <- character(0) last_names <- character(0) ages <- numeric(0) departments <- character(0) salaries <- numeric(0) # Get employee details from the user for (i in 1:5) { cat("Enter details for Employee", i, "\n") employee_ids[i] <- as.numeric(readline(prompt = "Employee ID: ")) first_names[i] <- readline(prompt = "First Name: ") last_names[i] <- readline(prompt = "Last Name: ") ages[i] <- as.numeric(readline(prompt = "Age: ")) departments[i] <- readline(prompt = "Department: ") salaries[i] <- as.numeric(readline(prompt = "Salary: ")) cat("\n") } # Create a data frame with employee details employee_data <- data.frame( EmployeeID = employee_ids, FirstName = first_names, LastName = last_names, Age = ages, Department = departments, Salary = salaries ) # Display the employee details print(employee_data) 8a # Sample data for two groups group1 <- c(18, 22, 19, 24, 25, 21, 20, 23, 19, 26) group2 <- c(16, 19, 17, 21, 18, 20, 22, 18, 15, 23) EXPERIMENT: 8A Write a R Program to perform t-tests for hypothesis testing on two groups of data. # Perform independent two-sample t-test t_test_result <- t.test(group1, group2) # Display t-test results cat("Independent Two-Sample T-Test Results:\n") cat("=====================================\n") cat("Group 1 Mean:", mean(group1), "\n") cat("Group 2 Mean:", mean(group2), "\n") cat("T-Statistic:", t_test_result$statistic, "\n") cat("P-Value:", t_test_result$p.value, "\n") # Determine significance level alpha <- 0.05 cat("\nSignificance Level (alpha):", alpha, "\n") # Check if the null hypothesis is rejected if (t_test_result$p.value < alpha) { cat("Null Hypothesis Rejected: There is a significant difference between the groups.\n") } else { cat("Null Hypothesis Not Rejected: There is no significant difference between the groups.\n") } 8b EXPERIMENT: 8B Program to conduct linear regression analysis and interpret the results. # Sample dataset data <- data.frame( X = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), Y = c(3, 6, 8, 10, 12, 15, 17, 19, 22, 24) ) # Perform linear regression analysis lm_model <- lm(Y ~ X, data = data) # Display linear regression summary summary(lm_model) 9a # Load necessary libraries EXPERIMENT :9A Write a R Program to analyze and visualize trends in time series data using the forecast package. library(forecast) # Load the AirPassengers dataset data("AirPassengers") # Convert the data to a time series object ts_data <- ts(AirPassengers, frequency = 12) # Plot the original time series data plot(ts_data, main = "AirPassengers Time Series Data", xlab = "Year", ylab = "Passengers") # Decompose the time series into trend, seasonal, and remainder components decomposed <- decompose(ts_data) # Plot the decomposed components plot(decomposed) # Forecast using Holt-Winters exponential smoothing forecast_hw <- forecast(ts_data, h = 24, method = "ets") # Plot the forecast plot(forecast_hw, main = "AirPassengers Forecast (Holt-Winters)", xlab = "Year", ylab = "Passengers") 9b EXPERIMENT 9B: Write a R Program to import data from an Excel file using the readxl package. # Load necessary library library(readxl) # Set the path to the Excel file excel_file <- "path_to_your_file/employee_data.xlsx" # Replace with the actual file path # Read data from the Excel file employee_data <- read_excel(excel_file, sheet = "Employees") # Display the imported employee data print(employee_data) 10 Write a R progra to implement object-oriented programming where the user provides input to create and manipulate bank account objects # Define a constructor function for creating a new bank account create_account <- function(owner, balance) { account <- list(owner = owner, balance = balance) class(account) <- "account" return(account) } # Define methods for the bank account class deposit <- function(account, amount) { if (amount > 0) { account$balance <- account$balance + amount cat("Deposited:", amount, "New balance:", account$balance, "\n") } else { cat("Invalid deposit amount.\n") } } withdraw <- function(account, amount) { if (amount > 0 && amount <= account$balance) { account$balance <- account$balance - amount cat("Withdrawn:", amount, "New balance:", account$balance, "\n") } else { cat("Invalid withdrawal amount or insufficient balance.\n") } } # Function to interact with a bank account interact_with_account <- function() { cat("Enter account owner's name: ") owner <- readline() cat("Enter initial balance: ") balance <- as.numeric(readline()) account <- create_account(owner, balance) cat("\n") cat("Account created for", owner, "with initial balance:", balance, "\n") repeat { cat("\n") cat("Choose an action:\n") cat("1. Deposit\n") cat("2. Withdraw\n") cat("3. Exit\n") choice <- as.integer(readline()) if (choice == 1) { cat("Enter deposit amount: ") amount <- as.numeric(readline()) deposit(account, amount) } else if (choice == 2) { cat("Enter withdrawal amount: ") amount <- as.numeric(readline()) withdraw(account, amount) } else if (choice == 3) { cat("Exiting...\n") break } else { cat("Invalid choice. Please select again.\n") } } } # Interact with a bank account interact_with_account()