0% found this document useful (0 votes)
66 views22 pages

Lab Programs

Uploaded by

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

Lab Programs

Uploaded by

gayathrinaik12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1.

Write a R program to find Area and Circumference of Circle

# Function to calculate the area of a circle

calculate_area<- function(radius)

area <- pi * radius^2

return(area)

# Function to calculate the circumference of a circle

calculate_circumference<- function(radius)

circumference <- 2 * pi * radius

return(circumference)

# Main program

main <- function() {

# Ask the user to input the radius

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

# Calculate area and circumference

area <- calculate_area(radius)

circumference <- calculate_circumference(radius)

# Print the results

cat("For a circle with radius", radius, ":\n")

cat("Area is:", area, "\n")

cat("Circumference is:", circumference, "\n")

# Run the main program

main()
2. Write an R program Illustrate with if-else statement and how does it operate on vectors of
variable length

# Simple if-else example

num<- as.numeric(readline(prompt="Enter a number: "))

if (num> 0) {

cat("The number is positive.\n")

} else if (num< 0) {

cat("The number is negative.\n")

} else {

cat("The number is zero.\n")

# Vector of numbers

numbers <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

# Use ifelse to check if each number is even or odd

result <- ifelse(numbers %% 2 == 0, "Even", "Odd")

# Print the result

cat("Numbers:", numbers, "\n")

cat("Even or Odd:", result, "\n")

# Vector of numbers with mixed signs

numbers <- c(-5, 0, 3, -1, 8, -7, 0, 2, 0, -3)

# Use ifelse to categorize each number

result <- ifelse(numbers > 0, "Positive",

ifelse(numbers < 0, "Negative", "Zero"))

# Print the result

cat("Numbers:", numbers, "\n")

cat("Categories:", result, "\n")


prog 2

# Define a function that checks whether each element of a vector is positive, negative, or zero

check_sign <- function(vec) {

# Initialize a result vector of the same length

result <- vector("character", length(vec))

# Loop through each element in the vector

for (i in seq_along(vec)) {

if (vec[i] > 0) {

result[i] <- "Positive"

} else if (vec[i] < 0) {

result[i] <- "Negative"

} else {

result[i] <- "Zero"

return(result)

# Create vectors of different lengths

vec1 <- c(1, -2, 0, 3, -5)

vec2 <- c(-1, 2, 0)

vec3 <- c(0, 0, 0, 0, 0, 0)

# Apply the function to each vector

result1 <- check_sign(vec1)

result2 <- check_sign(vec2)

result3 <- check_sign(vec3)

# Print the results

print(result1)

print(result2)
print(result3)

3. Write an R program Illustrate with for loop and stop on condition, to print the error message.

Prog 3
for (i in 1:10) {
if (i < 3)
next

print(i)

if (i >= 5)
print(“ error occurred”)
break

# Example vector to iterate over

values <- c(1, 2, 3, 2, 5, 1, 7)

# Loop through the vector and stop on a specific condition

for (i in 1:length(values)) {

# Check if the current value is less than or equal to 0

if (values[i] <= 0) {

# Print the error message and stop the execution

stop(paste("Error: Found a non-positive value at index", i, "with value", values[i]))

} else {

# Print the current value if it's positive

print(paste("Value at index", i, "is", values[i]))

4. Write an R Program to find Factorial of given numer

# take input from the user

num = as.integer(readline(prompt="Enter a number: "))

factorial = 1

# check is the number is negative, positive or zero


if(num < 0) {

print("Sorry, factorial does not exist for negative numbers")

} else if(num == 0) {

print("The factorial of 0 is 1")

} else {

for(i in 1:num) {

factorial = factorial * i

print(paste("The factorial of", num ,"is",factorial))

findfactorial <- function(n){

factorial <- 1

if ((n==0)|(n==1))
factorial <- 1

else{
for( i in 1:n)
factorial <- factorial * i
}
return (factorial)

5. Write an R Program to append a value to given empty vector


# Define an empty vector
vector <- c()

# Values to append
values <- c('a', 'b', 'c', 'd', 'e', 'f', 'g')

# Append each value to the vector


for (i in 1:length(values)) {
vector[i] <- values[i]
}

# Print the resulting vector


print(vector)

6. Implementation of Vectors data objects operations.

# Create vectors

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

char_vector <- c("a", "b", "c", "d")

logical_vector <- c(TRUE, FALSE, TRUE, FALSE)


# Access elements

vec <- c(10, 20, 30, 40, 50)

first_element <- vec[1]

first_three_elements <- vec[1:3]

elements_greater_than_20 <- vec[vec > 20]

# Arithmetic operations

vec1 <- c(1, 2, 3)

vec2 <- c(4, 5, 6)

sum_vector <- vec1 + vec2

diff_vector <- vec2 - vec1

prod_vector <- vec1 * vec2

div_vector <- vec2 / vec1

# Sequence and replication

sequence <- seq(1, 10)

sequence_step <- seq(1, 10, by=2)

rep_vector <- rep(1, times=5)

rep_each_vector <- rep(c(1, 2, 3), each=2)

# Logical operations

logical_vec1 <- c(TRUE, FALSE, TRUE)

logical_vec2 <- c(FALSE, FALSE, TRUE)

and_vector <- logical_vec1 & logical_vec2

or_vector <- logical_vec1 | logical_vec2

not_vector <- !logical_vec1

# Vector functions

sum_vec <- sum(vec)

mean_vec <- mean(vec)

min_val <- min(vec)

max_val <- max(vec)


sorted_vec <- sort(vec)

# Combine vectors

combined_vector <- c(vec1, vec2)

# Print results

print("First element:")

print(first_element)

print("First three elements:")

print(first_three_elements)

print("Elements greater than 20:")

print(elements_greater_than_20)

print("Sum of vectors:")

print(sum_vector)

print("Difference of vectors:")

print(diff_vector)

print("Product of vectors:")

print(prod_vector)

print("Division of vectors:")

print(div_vector)

print("Sequence from 1 to 10:")

print(sequence)

print("Sequence from 1 to 10 with step 2:")

print(sequence_step)

print("Replicate 1 five times:")

print(rep_vector)

print("Replicate each element in c(1, 2, 3) twice:")

print(rep_each_vector)

print("Logical AND of vectors:")

print(and_vector)

print("Logical OR of vectors:")

print(or_vector)

print("Logical NOT of vector:")


print(not_vector)

print("Sum of elements in vec:")

print(sum_vec)

print("Mean of elements in vec:")

print(mean_vec)

print("Minimum value in vec:")

print(min_val)

print("Maximum value in vec:")

print(max_val)

print("Sorted vec:")

print(sorted_vec)

print("Combined vector:")

print(combined_vector)

7.

1. # Matrices

numeric_matrix <- matrix(1:9, nrow=3, ncol=3)

char_matrix <- matrix(c("a", "b", "c", "d", "e", "f"), nrow=2, ncol=3)

logical_matrix <- matrix(c(TRUE, FALSE, TRUE, FALSE, TRUE, FALSE), nrow=2, ncol=3)

element <- numeric_matrix[2, 3]

row <- numeric_matrix[1, ]

column <- numeric_matrix[, 2]

transpose_matrix <- t(numeric_matrix)

matrix1 <- matrix(1:4, nrow=2, ncol=2)

matrix2 <- matrix(5:8, nrow=2, ncol=2)

product_matrix <- matrix1 %*% matrix2

sum_matrix <- matrix1 + matrix2

diff_matrix <- matrix1 - matrix2

prod_matrix <- matrix1 * matrix2


div_matrix <- matrix1 / matrix2

# Print results

print("Numeric matrix:")

print(numeric_matrix)

print("Character matrix:")

print(char_matrix)

print("Logical matrix:")

print(logical_matrix)

print("Element at 2nd row, 3rd column of numeric matrix:")

print(element)

print("1st row of numeric matrix:")

print(row)

print("2nd column of numeric matrix:")

print(column)

print("Transpose of numeric matrix:")

print(transpose_matrix)

print("Product of matrix1 and matrix2:")

print(product_matrix)

print("Sum of matrix1 and matrix2:")

print(sum_matrix)

print("Difference of matrix1 and matrix2:")

print(diff_matrix)

print("Product of matrix1 and matrix2 element-wise:")

print(prod_matrix)

print("Division of matrix1 and matrix2 element-wise:")

print(div_matrix)

2.

# Arrays

numeric_array <- array(1:27, dim=c(3, 3, 3))


array_element <- numeric_array[1, 2, 3]

array_row <- numeric_array[1, , 2]

array_column <- numeric_array[, 2, ]

# Print results

print("Numeric array:")

print(numeric_array)

print("Element at 1st row, 2nd column, 3rd layer of numeric array:")

print(array_element)

print("1st row of 2nd layer of numeric array:")

print(array_row)

print("2nd column of all layers of numeric array:")

print(array_column)

3.

# Factors

char_vector <- c("apple", "banana", "apple", "cherry", "banana")

fruit_factor <- factor(char_vector)

factor_levels <- levels(fruit_factor)

factor_element <- fruit_factor[3]

# Print results

print("Factor levels:")

print(factor_levels)

print("3rd element of factor:")

print(factor_element)

8. Write an R Program to Find Mean, Mode & Median.

#Mean
v <- c(10, 15, 20, 25, 30, 35)

cat("The vector contains:\n")

print(v)

cat("mean of all elements of the vector:", mean(v), "\n")

m <- matrix(c(10, 20, 30, 40, 50, 60), ncol=2)

cat("\nThe matrix contains:\n")

print(m)

cat("mean of all elements of the matrix:", mean(m))

cat("\nmean along first column of the matrix:", mean(m[,1]))

#Median

v <- c(10, 15, 20, 25, 30, 35)

cat("\nThe vector contains:\n")

print(v)

cat("median of the vector:", median(v), "\n")

m <- matrix(c(10, 20, 30, 40, 50, 60), ncol=2)

cat("\nThe matrix contains:\n")

print(m)

cat("median of the matrix:", median(m))

cat("\nmedian along first column of the matrix:", median(m[,1]))

# Mode

#creating a function to calculate mode

Mode <- function(x) {

uniqx <- unique(x)

uniqx[which.max(tabulate(match(x, uniqx)))]

}
#creating a vector with numbers

v1 <- c(10, 20, 30, 40, 30, 30, 50)

#creating a vector with characters

v2 <- c("this", "is", "a", "dog", "this", "this")

#calculating mode of vector v1

cat("mode of vector v1:", Mode(v1), "\n")

#calculating mode of vector v2

cat("mode of vector v2:", Mode(v2), "\n")

Part B programs
1. Write an R Program to implement T-Test

# Sample data for one-sample t-test

one_sample_data <- c(5.1, 5.8, 6.0, 5.5, 5.7, 5.6, 6.1, 5.9)

# Perform one-sample t-test

# Test if the mean of the sample data is equal to a specific value (e.g., 5.5)

one_sample_ttest <- t.test(one_sample_data, mu = 5.5)

# Print the result of one-sample t-test

print("One-Sample T-Test Result:")

print(one_sample_ttest)

# Sample data for two-sample t-test

group1 <- c(5.1, 5.8, 6.0, 5.5, 5.7, 5.6, 6.1, 5.9)

group2 <- c(5.3, 5.9, 6.2, 5.6, 5.8, 5.7, 6.3, 6.0)

# Perform two-sample t-test

# Test if the means of two independent groups are equal

two_sample_ttest <- t.test(group1, group2)

# Print the result of two-sample t-test

print("Two-Sample T-Test Result:")

print(two_sample_ttest)
2. Write an R Program Compute mean values for vector aggregates defined by factors tapply and
sapply.

# Sample data

values <- c(5.1, 5.8, 6.0, 5.5, 5.7, 5.6, 6.1, 5.9, 5.3, 5.9, 6.2, 5.6)

factors <- gl(3, 4) # Generate factor levels

# Compute mean values using tapply

mean_values_tapply <- tapply(values, factors, mean)

# Print the result of tapply

print("Mean values using tapply:")

print(mean_values_tapply)

# Sample data for sapply example

data_list <- list(

group1 = c(5.1, 5.8, 6.0, 5.5),

group2 = c(5.7, 5.6, 6.1, 5.9),

group3 = c(5.3, 5.9, 6.2, 5.6)

# Compute mean values using sapply

mean_values_sapply <- sapply(data_list, mean)

# Print the result of sapply

print("Mean values using sapply:")

print(mean_values_sapply)
3. Write an R Program to find Unique element of a given string and unique value from vector.

# Function to find unique characters in a string

unique_chars_in_string <- function(input_string) {

# Split the string into individual characters

char_vector <- strsplit(input_string, NULL)[[1]]

# Find unique characters

unique_chars <- unique(char_vector)

return(unique_chars)

# Function to find unique values in a vector

unique_values_in_vector <- function(input_vector) {

# Find unique values

unique_values <- unique(input_vector)

return(unique_values)

# Example usage

# Unique characters in a string

input_string <- "hello world"

unique_chars <- unique_chars_in_string(input_string)

print("Unique characters in the string:")

print(unique_chars)

# Unique values in a vector

input_vector <- c(1, 2, 3, 2, 4, 1, 5, 3, 6, 4)

unique_values <- unique_values_in_vector(input_vector)

print("Unique values in the vector:")

print(unique_values)
4. Write a R program to demonstrate Binomial Distribution.

# Install ggplot2 if not already installed

if (!require(ggplot2)) {

install.packages("ggplot2")

library(ggplot2)

# Parameters for the Binomial Distribution

n <- 10 # Number of trials

p <- 0.5 # Probability of success on each trial

# Generate binomial random variables

set.seed(123) # Set seed for reproducibility

binom_samples <- rbinom(1000, n, p)

# Calculate binomial probabilities

x <- 0:n

binom_prob <- dbinom(x, n, p)

# Print binomial probabilities

print("Binomial probabilities:")

print(data.frame(x = x, Probability = binom_prob))

# Plot the binomial distribution

binom_df <- data.frame(Successes = x, Probability = binom_prob)

ggplot(binom_df, aes(x = Successes, y = Probability)) +

geom_bar(stat = "identity", fill = "skyblue") +

labs(title = "Binomial Distribution",

x = "Number of Successes",

y = "Probability") +

theme_minimal()
# Plot histogram of binomial samples

ggplot(data.frame(Samples = binom_samples), aes(x = Samples)) +

geom_histogram(binwidth = 1, fill = "lightgreen", color = "black") +

labs(title = "Histogram of Binomial Samples",

x = "Number of Successes",

y = "Frequency") +

theme_minimal()

5. Write a R program to demonstrate Normal Distribution.

# Load necessary library

library(ggplot2)

# Parameters for the Normal Distribution

mean <- 0 # Mean of the distribution

sd <- 1 # Standard deviation of the distribution

# Generate normal random variables

set.seed(123) # Set seed for reproducibility

norm_samples <- rnorm(1000, mean, sd)

# Calculate normal density

x <- seq(-4, 4, length.out = 100)

norm_density <- dnorm(x, mean, sd)

# Print a summary of the generated normal samples

print("Summary of normal samples:")

print(summary(norm_samples))

# Plot the normal distribution

norm_df <- data.frame(x = x, Density = norm_density)


ggplot(norm_df, aes(x = x, y = Density)) +

geom_line(color = "blue") +

labs(title = "Normal Distribution",

x = "Value",

y = "Density") +

theme_minimal()

# Plot histogram of normal samples with the density curve

ggplot(data.frame(Samples = norm_samples), aes(x = Samples)) +

geom_histogram(aes(y = ..density..), binwidth = 0.2, fill = "lightblue", color = "black") +

stat_function(fun = dnorm, args = list(mean = mean, sd = sd), color = "red", size = 1) +

labs(title = "Histogram of Normal Samples with Density Curve",

x = "Value",

y = "Density") +

theme_minimal()

6. Write an R Program Illustrate Reading & Writing Files.

# Reading and Writing CSV Files

# Create a sample data frame

sample_data <- data.frame(

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

Age = c(28, 34, 23, 45),

Height = c(5.8, 5.5, 6.0, 5.6)

# Write the data frame to a CSV file

write.csv(sample_data, "sample_data.csv", row.names = FALSE)


# Read the data from the CSV file

read_data_csv <- read.csv("sample_data.csv")

# Print the data read from the CSV file

print("Data read from CSV file:")

print(read_data_csv)

# Reading and Writing Text Files

# Create a sample text

sample_text <- "This is an example of writing and reading text files in R."

# Write the sample text to a text file

writeLines(sample_text, "sample_text.txt")

# Read the data from the text file

read_data_txt <- readLines("sample_text.txt")

# Print the data read from the text file

print("Data read from text file:")

print(read_data_txt)
7. Write a R program for simple bar plot for 5 subject marks

# Load necessary library

if (!require(ggplot2)) {

install.packages("ggplot2")

library(ggplot2)

# Sample data for 5 subject marks

subjects <- c("Math", "Science", "English", "History", "Art")

marks <- c(85, 90, 78, 88, 92)

# Create a data frame

data <- data.frame(Subject = subjects, Marks = marks)

# Create a bar plot

p <- ggplot(data, aes(x = Subject, y = Marks)) +

geom_bar(stat = "identity", fill = "SKYBLUE") +

labs(title = "Marks in 5 Subjects",

x = "Subject",

y = "Marks") +

theme_minimal()

# Print the plot

print(p)

# For environments other than RStudio, you might need to explicitly print the plot

if (interactive()) {

print(p)

} else {

ggsave("bar_plot.png", plot = p)

}
8. Implementation of Data visualization using ggplot.

# Load necessary library

if (!require(ggplot2)) {

install.packages("ggplot2")

library(ggplot2)

# Load the mtcars dataset

data("mtcars")

# Scatter Plot

scatter_plot <- ggplot(mtcars, aes(x = wt, y = mpg)) +

geom_point(color = "blue") +

labs(title = "Scatter Plot of MPG vs Weight",

x = "Weight (1000 lbs)",

y = "Miles per Gallon (MPG)") +

theme_minimal()

print(scatter_plot)

# Bar Plot

bar_plot <- ggplot(mtcars, aes(x = factor(cyl))) +

geom_bar(fill = "orange") +

labs(title = "Bar Plot of Cylinder Counts",

x = "Number of Cylinders",

y = "Count") +

theme_minimal()

print(bar_plot)

# Line Plot

line_plot <- ggplot(mtcars, aes(x = hp, y = mpg)) +

geom_line(color = "green") +
labs(title = "Line Plot of MPG vs Horsepower",

x = "Horsepower (HP)",

y = "Miles per Gallon (MPG)") +

theme_minimal()

print(line_plot)

# Histogram

histogram <- ggplot(mtcars, aes(x = mpg)) +

geom_histogram(binwidth = 2, fill = "purple", color = "black") +

labs(title = "Histogram of MPG",

x = "Miles per Gallon (MPG)",

y = "Frequency") +

theme_minimal()

print(histogram)

# Box Plot

box_plot <- ggplot(mtcars, aes(x = factor(cyl), y = mpg)) +

geom_boxplot(fill = "lightblue") +

labs(title = "Box Plot of MPG by Cylinder Count",

x = "Number of Cylinders",

y = "Miles per Gallon (MPG)") +

theme_minimal()

print(box_plot)

You might also like