Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
20 views21 pages

R Lab Program

The program contains functions to create different data structures like vectors, lists, matrices, data frames, factors and arrays in R. It allows the user to select a data structure and the function will create and return the selected structure.

Uploaded by

Sachin Shimogha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views21 pages

R Lab Program

The program contains functions to create different data structures like vectors, lists, matrices, data frames, factors and arrays in R. It allows the user to select a data structure and the function will create and return the selected structure.

Uploaded by

Sachin Shimogha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

1.Write an R program for different types of data structures in R.

# Function to create different data structures based on user choice

create_data_structure <- function(choice) {

switch(

choice,

"1" = {

# Creating a vector

numbers <- c(1, 2, 3, 4, 5)

# Displaying the vector

cat("Original Vector: ", numbers, "\n")

# Performing operations on the vector

# Doubling each element

doubled_numbers <- numbers * 2

cat("Doubled Vector: ", doubled_numbers, "\n")

# Summing up the elements

sum_of_numbers <- sum(numbers)

cat("Sum of Vector Elements: ", sum_of_numbers, "\n")

# Finding the mean

mean_of_numbers <- mean(numbers)

cat("Mean of Vector Elements: ", mean_of_numbers, "\n")

# Accessing specific elements by index

index_3 <- numbers[3]


cat("Element at Index 3: ", index_3, "\n")

},

2" = {

# Create a list with different types of elements

my_list <- list(

name = "John",

age = 25,

grades = c(90, 85, 92),

has_passed = TRUE

rint the original list

print("Original List:")

print(my_list)

ccess and print specific elements from the list

print("Name:", my_list$name)

print("Age:", my_list$age)

print("Grades:", my_list$grades)

print("Has Passed:", my_list$has_passed)

# Add a new element to the list

my_list$course <- "Math"

print("List after adding a new element:")

print(my_list)

# Modify an existing element in the list

my_list$age <- 26

print("List after modifying the 'age' element:")


print(my_list)

# Remove an element from the list

my_list$course <- NULL

print("List after removing the 'course' element:")

print(my_list)

# Return the list

return(my_list)

},

"3" = {

# Create a matrix with numeric values

my_matrix <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3, byrow = TRUE)

# Print the original matrix

print("Original Matrix:")

print(my_matrix)

# Calculate and print the transpose of the matrix

transposed_matrix <- t(my_matrix)

print("Transposed Matrix:")

print(transposed_matrix)

# Calculate and print the sum of each column in the matrix

column_sums <- colSums(my_matrix)

print("Column Sums:")

print(column_sums)
# Calculate and print the product of each row in the matrix

row_products <- apply(my_matrix, 1, prod)

print("Row Products:")

print(row_products)

# Multiply the matrix by a scalar

scalar <- 2

scaled_matrix <- my_matrix * scalar

print(paste("Matrix multiplied by scalar", scalar, ":"))

print(scaled_matrix)

# Perform element-wise squaring of the matrix

squared_matrix <- my_matrix^2

print("Squared Matrix:")

print(squared_matrix)

},

"4" = {

# Create a data frame

my_dataframe <- data.frame(

Name = c("John", "Alice", "Bob"),

Age = c(25, 30, 28),

Score = c(90, 85, 92)

# Print the original data frame


print("Original Data Frame:")

print(my_dataframe)

# Access and print specific columns from the data frame

print("Names:")

print(my_dataframe$Name)

print("Ages:")

print(my_dataframe$Age)

print("Scores:")

print(my_dataframe$Score)

# Add a new column to the data frame

my_dataframe$Grade <- c("A", "B", "A")

print("Data Frame after adding a new column:")

print(my_dataframe)

# Modify an existing column in the data frame

my_dataframe$Age <- c(26, 31, 29)

print("Data Frame after modifying the 'Age' column:")

print(my_dataframe)

# Remove a column from the data frame

my_dataframe$Grade <- NULL

print("Data Frame after removing the 'Grade' column:")

print(my_dataframe)

# Calculate and print summary statistics of the data frame

summary_stats <- summary(my_dataframe)


print("Summary Statistics:")

print(summary_stats)

},

"5" = {

# Create a factor

gender <- factor(c("Male", "Female", "Male", "Female"))

# Print the original factor

print("Original Factor:")

print(gender)

# Print the levels of the factor

print("Factor Levels:")

print(levels(gender))

# Print the frequency of each level in the factor

print("Frequency of Each Level:")

print(table(gender))

# Change the order of factor levels

gender <- factor(gender, levels = c("Female", "Male"))

print("Factor with Changed Level Order:")

print(gender)

# Add a new level to the factor

gender <- factor(gender, levels = c(levels(gender), "Non-Binary"))

print("Factor with Added Level:")


print(gender)

# Remove a level from the factor

gender <- factor(gender, exclude = "Non-Binary")

print("Factor with Removed Level:")

print(gender)

},

"6" = {

# Create an array

my_array <- array(1:24, dim = c(2, 3, 4))

# Print the original array

print("Original Array:")

print(my_array)

# Access and print specific elements from the array

print("Element at position (1, 2, 3):")

print(my_array[1, 2, 3])

# Calculate and print the sum of the array along each dimension

sum_along_dim1 <- apply(my_array, 1, sum)

sum_along_dim2 <- apply(my_array, 2, sum)

sum_along_dim3 <- apply(my_array, 3, sum)

print("Sum along Dimension 1:")

print(sum_along_dim1)

print("Sum along Dimension 2:")


print(sum_along_dim2)

print("Sum along Dimension 3:")

print(sum_along_dim3)

# Multiply the entire array by a scalar

scalar <- 2

scaled_array <- my_array * scalar

print(paste("Array multiplied by scalar", scalar, ":"))

print(scaled_array)

# Perform element-wise squaring of the array

squared_array <- my_array^2

print("Squared Array:")

print(squared_array)

},

warning("Invalid choice. No data structure created.")

# Get user choice

print("Choose a data structure:")

print("1. Vector")

print("2. List")

print("3. Matrix")

print("4. Data Frame")

print("5. Factor")
print("6. Array")

user_choice <- readline(prompt = "Enter the number corresponding to your choice: ")

# Create and print the selected data structure

result <- create_data_structure(user_choice)

print("\nResult:")

print(result)

2.Write an R program that includes variables, constants, and data types.

# Constants

PI <- 3.14159

# Function to calculate the area of a circle

calculate_circle_area <- function(radius) {

return(PI * radius^2)

# Function to calculate the area of a rectangle

calculate_rectangle_area <- function(length, width) {

return(length * width)

# Function to calculate the area of a triangle

calculate_triangle_area <- function(base, height) {

return(0.5 * base * height)

}
# Main program

cat("Choose a shape:\n")

cat("1. Circle\n")

cat("2. Rectangle\n")

cat("3. Triangle\n")

cat("4. Exit\n")

shape_choice <- as.numeric(readline(prompt = "Enter the number corresponding to your


choice: "))

if (shape_choice == 1) {

# Circle

radius <- as.numeric(readline(prompt = "Enter the radius of the circle: "))

area_circle <- calculate_circle_area(radius)

cat("Area of the Circle:", area_circle, "\n")

} else if (shape_choice == 2) {

# Rectangle

length_rectangle <- as.numeric(readline(prompt = "Enter the length of the rectangle: "))

width_rectangle <- as.numeric(readline(prompt = "Enter the width of the rectangle: "))

area_rectangle <- calculate_rectangle_area(length_rectangle, width_rectangle)

cat("Area of the Rectangle:", area_rectangle, "\n")

} else if (shape_choice == 3) {

# Triangle

base_triangle <- as.numeric(readline(prompt = "Enter the base of the triangle: "))

height_triangle <- as.numeric(readline(prompt = "Enter the height of the triangle: "))

area_triangle <- calculate_triangle_area(base_triangle, height_triangle)

cat("Area of the Triangle:", area_triangle, "\n")


} else {

cat("Invalid choice. Please choose a valid shape.\n")

3.Write an R program that includes different operators, control structures, default values for
arguments, returning complex objects.

#Function with default argument values and complex object return

calculate_values <- function(a = 5, b = 10) {

# Arithmetic operations

sum <- a + b

difference <- a - b

product <- a * b

quotient <- a / b

# Comparison operators

greater_than <- a > b

less_than <- a < b

equal_to <- a == b

# Control structures (if-else)

if (greater_than) {

result <- paste(a, "is greater than", b)

} else if (less_than) {

result <- paste(a, "is less than", b)

} else {

result <- paste(a, "is equal to", b)


}

# Complex object return

values <- list(

sum = sum,

difference = difference,

product = product,

quotient = quotient,

comparison = result

return(values)

# Calling the function with default arguments

result <- calculate_values()

# Printing the returned complex object

print(result)

4.Write an R program for quick sort implementation.

quickSort <- function(arr) {

if (length(arr) <= 1) {

return(arr)

} else {

pivot <- arr[1]

less <- arr[arr < pivot]


equal <- arr[arr == pivot]

greater <- arr[arr > pivot]

return(c(quickSort(less), equal, quickSort(greater)))

# Take user input for the array

cat("Enter elements of the array separated by spaces: ")

userInput <- readline()

myArray <- as.numeric(strsplit(userInput, " ")[[1]])

# Check if the user entered valid numeric values

if (any(is.na(myArray))) {

cat("Invalid input. Please enter numeric values.\n")

} else {

sortedArray <- quickSort(myArray)

cat("Original Array: ", myArray, "\n")

cat("Sorted Array: ", sortedArray, "\n")

5.Write a R program for calculating cumulative sums, and products minima,maxima

# Function to calculate cumulative sums, products, minima, and maxima

calculateStatistics <- function(vec) {

cumulativeSum <- cumsum(vec)

cumulativeProduct <- cumprod(vec)


minValues <- cummin(vec)

maxValues <- cummax(vec)

result <- list(

CumulativeSum = cumulativeSum,

CumulativeProduct = cumulativeProduct,

MinValues = minValues,

MaxValues = maxValues

return(result)

# Example usage

myVector <- c(2, 4, 6, 8, 10)

statistics <- calculateStatistics(myVector)

cat("Original Vector: ", myVector, "\n")

cat("Cumulative Sum: ", statistics$CumulativeSum, "\n")

cat("Cumulative Product: ", statistics$CumulativeProduct, "\n")

cat("Min Values: ", statistics$MinValues, "\n")

cat("Max Values: ", statistics$MaxValues, "\n")

6. Write an R program for finding stationary distribution of markov chains.

# Install and load the markovchain package

# install.packages("markovchain")
library(markovchain)

# Define the transition matrix for your Markov chain

transitionMatrix <- matrix(c(0.7, 0.3, 0.2, 0.8), nrow = 2, byrow = TRUE)

# Create a Markov chain object

myMarkovChain <- new("markovchain", states = c("State1", "State2"), transitionMatrix =


transitionMatrix, name = "MyMarkovChain")

# Find the stationary distribution

stationaryDistribution <- steadyStates(myMarkovChain)

# Print the results

cat("Transition Matrix:\n", transitionMatrix, "\n\n")

cat("Stationary Distribution:\n", stationaryDistribution, "\n")

7. Write an R program that includes linear algebra operations on vectors and matrices.

# Creating vectors

vector_a <- c(1, 2, 3)

vector_b <- c(4, 5, 6)

# Creating matrices

matrix_A <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, byrow = TRUE)

matrix_B <- matrix(c(7, 8, 9, 10, 11, 12), nrow = 2, byrow = TRUE)

# Vector addition

vector_sum <- vector_a + vector_b

print("Vector Addition:")
print(vector_sum)

# Vector dot product

dot_product <- sum(vector_a * vector_b)

print("Vector Dot Product:")

print(dot_product)

# Matrix addition

matrix_sum <- matrix_A + matrix_B

print("Matrix Addition:")

print(matrix_sum)

# Matrix multiplication

matrix_product <- matrix_A %*% t(matrix_B)

print("Matrix Multiplication:")

print(matrix_product)

8. Write a R program for any visual representation of an object with creating graphs using
graphic functions: Plot(), Hist(), Linechart(), Pie(), Boxplot(), Scatterplots().

# Generate sample data

set.seed(123)

data <- rnorm(100)

# Create a sequence for x-axis

x <- seq(1, 100, by = 1)

# Function to generate plots based on user choice

generatePlot <- function(choice) {


switch(

choice,

"1" = {

# Line Chart

plot(x, data, type = "l", col = "blue", main = "Line Chart", xlab = "X-axis", ylab = "Y-axis")

},

"2" = {

# Histogram

hist(data, col = "green", main = "Histogram", xlab = "Value", ylab = "Frequency")

},

"3" = {

# Line chart (adding another line to the existing plot)

lines(x, 0.5 * data, col = "red")

# Additional line

legend("topright", legend = c("Line 1", "Line 2"), col = c("blue", "red"), lty = 1)

},

"4" = {

# Pie chart

pie(table(cut(data, breaks = 5)), main = "Pie Chart")

},

"5" = {

# Boxplot

boxplot(data, col = "orange", main = "Boxplot", ylab = "Values")

},

"6" = {

# Scatterplot

set.seed(456)

data2 <- rnorm(100)


plot(data, data2, col = "purple", main = "Scatterplot", xlab = "Data 1", ylab = "Data 2")

},

cat("Invalid choice. Please enter a number between 1 and 6.\n")

# Get user choice

cat("Choose a plot type:\n")

cat("1. Line Chart\n")

cat("2. Histogram\n")

cat("3. Line Chart with Two Lines\n")

cat("4. Pie Chart\n")

cat("5. Boxplot\n")

cat("6. Scatterplot\n")

choice <- readline(prompt = "Enter the number of your choice: ")

# Generate plot based on user choice

generatePlot(choice)

# Wait for user input before closing the graphics windows

cat("Press Enter to close the graphics windows.")

readline()

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.

# Load the iris dataset


data(iris)

# Display the first few rows of the dataset

head(iris)

# Indexing and subsetting data frames

# Selecting only the rows where Sepal.Length is greater than 5

subset_data <- iris[iris$Sepal.Length > 5, ]

# Display the subsetted data

print("Subset of data where Sepal.Length > 5:")

print(subset_data)

# Manipulating data

# Adding a new column "Petal.Area" by multiplying Petal.Length and Petal.Width

iris$Petal.Area <- iris$Petal.Length * iris$Petal.Width

# Display the modified dataset

print("Dataset with added Petal.Area column:")

head(iris)

# Analyzing data

# Summary statistics of the dataset

summary(iris)

# Mean of Sepal.Length grouped by Species

mean_sepal_length_by_species <- tapply(iris$Sepal.Length, iris$Species, mean)

print("Mean Sepal.Length by Species:")


print(mean_sepal_length_by_species)

# Plotting the data

# Scatter plot of Sepal.Length vs. Sepal.Width

plot(iris$Sepal.Length, iris$Sepal.Width, col = iris$Species, pch = 19, main = "Sepal.Length


vs. Sepal.Width", xlab = "Sepal.Length", ylab = "Sepal.Width", cex = 1.2)

legend("topright", legend = levels(iris$Species), col = 1:3, pch = 19, title = "Species")

10. Write a program to create an any application of Linear Regression in multivariate context
for predictive purpose.

# Generate sample data

set.seed(123)

n <- 100 # Number of observations

# Predictor variables

x1 <- rnorm(n, mean = 20, sd = 5)

x2 <- rnorm(n, mean = 30, sd = 8)

# Response variable with a linear relationship to predictors

y <- 2 * x1 + 3 * x2 + rnorm(n, mean = 0, sd = 10)

# Create a data frame

my_data <- data.frame(x1, x2, y)

# Explore the structure of the dataset

cat("Structure of the generated dataset:\n")

str(my_data)

cat("\n")
# Fit a multivariate linear regression model

linear_model <- lm(y ~ x1 + x2, data = my_data)

# Display the summary of the regression model

cat("Summary of the Linear Regression Model:\n")

summary(linear_model)

cat("\n")

# Predictive purposes: Make predictions on new data

new_data <- data.frame(x1 = c(22, 25, 18),

x2 = c(28, 35, 30))

predictions <- predict(linear_model, newdata = new_data)

# Display the predictions

cat("Predictions for new data:\n")

print(predictions)

cat("\n")

You might also like