0% found this document useful (0 votes)
9 views13 pages

R Programs for Temperature, Area, and Data Analysis

The document contains various R programming tasks including temperature conversion, area calculation of shapes, finding even numbers, string manipulation, data structures, reading CSV files, creating charts, statistical analysis, and recursive functions. Each task is accompanied by code snippets demonstrating the implementation of the respective functionality. The document serves as a comprehensive guide for performing basic programming operations in R.

Uploaded by

surekha
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)
9 views13 pages

R Programs for Temperature, Area, and Data Analysis

The document contains various R programming tasks including temperature conversion, area calculation of shapes, finding even numbers, string manipulation, data structures, reading CSV files, creating charts, statistical analysis, and recursive functions. Each task is accompanied by code snippets demonstrating the implementation of the respective functionality. The document serves as a comprehensive guide for performing basic programming operations in R.

Uploaded by

surekha
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.

Program to convert the given temperature from Fahrenheit to Celsius and vice versa
depending upon user’s choice.

AIM:

To write a program to convert the given temperature from Fahrenheit to


Celcius and vice versa.
PROCEDURE:

STEP 1:

# Convert Celsius to Fahrenheit


celsius_to_fahrenheit <- function(celsius) {
return((celsius * 9/5) + 32)
}

# Example: Convert 25 degrees Celsius to Fahrenheit


celsius_temp <- 25
fahrenheit_temp <- celsius_to_fahrenheit(celsius_temp)
cat(celsius_temp, "degrees Celsius is equal to", fahrenheit_temp, "Fahrenheit\n")
25 degrees Celsius is equal to 77 Fahrenheit

# Convert Fahrenheit to Celsius


fahrenheit_to_celsius <- function(fahrenheit) {
return((fahrenheit - 32) * 5/9)
}

# Example: Convert 77 degrees Fahrenheit to Celsius


fahrenheit_temp <- 77
celsius_temp <- fahrenheit_to_celsius(fahrenheit_temp)
cat(fahrenheit_temp, "degrees Fahrenheit is equal to", celsius_temp, "Celsius\n")
77 degrees Fahrenheit is equal to 25 Celsius

2. Program, to find the area of rectangle, square, circle and triangle by accepting suitable
input parameters from user.

# Function to calculate the area of a rectangle

rectangle_area <- function(length, width) {


return(length * width)

# Function to calculate the area of a square

square_area <- function(side) {

return(side * side)

# Function to calculate the area of a circle

circle_area <- function(radius) {

return(pi * radius^2)

# Function to calculate the area of a triangle

triangle_area <- function(base, height) {

return(0.5 * base * height)

# Main program

while (TRUE) {

cat("Select a shape to calculate its area:\n")

cat("1. Rectangle\n")

cat("2. Square\n")

cat("3. Circle\n")

cat("4. Triangle\n")

cat("5. Exit\n")

choice <- [Link](readline(prompt = "Enter your choice (1-5): "))


if (choice == 1) {

length <- [Link](readline(prompt = "Enter the length of the

rectangle: "))

width <- [Link](readline(prompt = "Enter the width of the

rectangle: "))

area <- rectangle_area(length, width)

cat("Area of the rectangle:", area, "\n")

} else if (choice == 2) {

side <- [Link](readline(prompt = "Enter the side of the square: "))

area <- square_area(side)

cat("Area of the square:", area, "\n")

} else if (choice == 3) {

radius <- [Link](readline(prompt = "Enter the radius of the circle:

"))

area <- circle_area(radius)

cat("Area of the circle:", area, "\n")

} else if (choice == 4) {

base <- [Link](readline(prompt = "Enter the base of the triangle:

"))

height <- [Link](readline(prompt = "Enter the height of the

triangle: "))

area <- triangle_area(base, height)

cat("Area of the triangle:", area, "\n")


} else if (choice == 5) {

break

} else {

cat("Invalid choice. Please try again.\n")

3. Write a program to find list of even numbers from 1 to n using R Loops.

find_even_numbers <- function(n) {


# Initialize an empty vector to store even numbers
even_numbers <- c()
# Loop from 1 to n
for (i in 1:n) {
# Check if the current number is even
if (i %% 2 == 0) {
# Add the even number to the vector
even_numbers <- c(even_numbers, i)
}
}

# Return the list of even numbers


return(even_numbers)
}

# Example usage:
n_value <- 20
result <- find_even_numbers(n_value)
print(paste("Even numbers from 1 to", n_value, "are:", paste(result, collapse = ",
")))

4. Create a function to print squares of numbers in sequence.


# Function to calculate the square of a number using a while loop
calculateSquare <- function(num) {
i <- 1
while (i <= num) {
square <- i * i
cat(i, "squared is", square, "\n")
i <- i + 1
}
}

# Example usage
input <- 10
calculateSquare(input)

5. Write a program to join columns and rows in a data frame using cbind() and rbind() in
R.

cbind()

# Create two sample data frames


df1 <- [Link](ID = c(1, 2, 3), Name = c("Arun", "Kumar", "Chandru"))
df2 <- [Link](Age = c(21, 22, 20), City = c("Chennai", "Vellore", "Ranipet"))

# View the original data frames


print("Data Frame 1:")
print(df1)
print("Data Frame 2:")
print(df2)

# Join the data frames by columns using cbind()


combined_cols_df <- cbind(df1, df2)

# View the resulting data frame


print("Data Frame after cbind():")
print(combined_cols_df)

rbind()

# Create two sample data frames with the same column names
df3 <- [Link](Name = c("Arun", "Kumar"), Age = c(21, 20))
df4 <- [Link](Name = c("Chandru", "Deepak"), Age = c(22, 21))

# View the original data frames


print("Data Frame 3:")
print(df3)
print("Data Frame 4:")
print(df4)

# Join the data frames by rows using rbind()


combined_rows_df <- rbind(df3, df4)

# View the resulting data frame


print("Data Frame after rbind():")
print(combined_rows_df)

6. Implement different String Manipulation functions in R.

string1 <- "Hello"


string2 <- "World"

# Concatenate with a space separator (default)


result_space <- paste(string1, string2)
print(result_space)

# Concatenate without any separator


result_nosep <- paste0(string1, string2) # paste0 is a shortcut for paste(..., sep = "")
print(result_nosep)

# Concatenate with a custom separator


result_custom_sep <- paste(string1, string2, sep = "-")
print(result_custom_sep)

my_string <- "R Programming"

# Extract characters from position 3 to 7


sub_string <- substr(my_string, start = 3, stop = 7)
print(sub_string)

sentence <- "This is a sample sentence."


word_list <- strsplit(sentence, " ")
print(word_list)
first_word <- word_list[[1]][1]
print(first_word)

text <- "apple banana apple orange"

# Replace the first "apple" with "grape"


new_text_sub <- sub("apple", "grape", text)
print(new_text_sub)

# Replace all "apple" with "grape"


new_text_gsub <- gsub("apple", "grape", text)
print(new_text_gsub)

short_string <- "R"


long_string <- "Programming Language"

length_short <- nchar(short_string)


print(length_short)

length_long <- nchar(long_string)


print(length_long)

7. Implement different data structures in R (Vectors, Lists, Data Frames)

# Numeric vector
numeric_vector <- c(1, 2, 3, 4, 5)
print(numeric_vector)
# Character vector
character_vector <- c("Apple", "Banana", "Orange")
print(character_vector)

# Logical vector
logical_vector <- c(TRUE, FALSE, TRUE, FALSE)
print(logical_vector)

# Creating a list with different data types


my_list <- list("Name" = "Arun",
"Age" = 20,
"Scores" = c(85, 92, 78),
"IsStudent" = TRUE)
print(my_list)

# Accessing elements of a list


print(my_list$Name)
print(my_list[[2]])
print(my_list[["Scores"]])

# Creating a data frame


employee_data <- [Link](
Name = c("Jeevan", "Kumar", "Mithun"),
Age = c(23, 22, 24),
Department = c("Sales", "Marketing", "IT"),
Salary = c(60000, 75000, 80000)
)
print(employee_data)

# Accessing columns of a data frame


print(employee_data$Name)
print(employee_data[["Age"]])

# Accessing rows of a data frame


print(employee_data[1, ]) # First row
print(employee_data[c(1, 3), ]) # First and third rows

8. Write a program to read a csv file and analyze the data in the file in R.

# read [Link] file from our current directory

read_data <- [Link]("[Link]")

# display csv file

print(read_data)

# read [Link] file from our directory

read_data <- [Link]("[Link]")

# print total number of columns

cat("Total Columns: ", ncol(read_data))

# print total number of rows

cat("Total Rows:", nrow(read_data))

9. Create pie chart and bar chart using R.

a) Pie Chart

marks<- c(68, 56, 75, 83)

names <- c("Manoj", "Pughazh", "Kamal", "Kughan")

pie(marks, names)

b) Bar Chart

A <- c(17, 2, 8, 13, 11, 22)

B <- c("Jan", "feb", "Mar", "Apr", "May", "Jun")

barplot(A, [Link] = B, xlab ="Month",


ylab ="Articles", col ="green",

main ="Month-Article chart")

10. Create a data set and do statistical analysis on the data using R.

# Create a data frame with some sample data


data_sample <- [Link](
ID = 1:10,
Age = c(25, 30, 22, 35, 28, 40, 32, 27, 33, 29),
Score = c(85, 92, 78, 95, 88, 70, 80, 90, 83, 87),
Gender = factor(c("Male", "Female", "Male", "Female", "Male", "Female",
"Male", "Female", "Male", "Female"))
)

# View the created dataset


print(data_sample)

# Summary statistics for numerical variables


summary(data_sample)
# Calculate mean, median, and standard deviation for 'Age'
mean_age <- mean(data_sample$Age)
median_age <- median(data_sample$Age)
sd_age <- sd(data_sample$Age)
cat("\nMean Age:", mean_age, "\n")
cat("Median Age:", median_age, "\n")
cat("Standard Deviation of Age:", sd_age, "\n")
# Calculate mean score by gender
mean_score_by_gender <- aggregate(Score ~ Gender, data = data_sample, FUN =
mean)
print(mean_score_by_gender)
# Perform a t-test to compare the mean scores between genders
t_test_result <- [Link](Score ~ Gender, data = data_sample)
print(t_test_result)
# Create a histogram of 'Score'
hist(data_sample$Score, main = "Distribution of Scores", xlab = "Score", col =
"lightblue")

11. Program to find factorial of the given number using recursive function.

# Define a function to calculate the factorial using recursion


factorial_recursive <- function(n) {
# Base case: Factorial of 0 is 1
if (n == 0) {
return(1)
}
# Recursive case: Calculate factorial using recursion
else {
return(n * factorial_recursive(n - 1))
}
}

# Example usage
number <- 5
result <- factorial_recursive(number)

# Print the result


cat("The factorial of", number, "is:", result, "\n")

# Another example
number_two <- 7
result_two <- factorial_recursive(number_two)
cat("The factorial of", number_two, "is:", result_two, "\n")

12. Write a R program to count the number of even and odd numbers from array of N
numbers.
# Function to count even and odd numbers in a numeric vector
count_even_odd <- function(numbers) {
# Initialize counters
even_count <- 0
odd_count <- 0

# Iterate through the numbers in the vector


for (num in numbers) {
if (num %% 2 == 0) {
even_count <- even_count + 1
} else {
odd_count <- odd_count + 1
}
}

# Return the counts as a named list


return(list(even = even_count, odd = odd_count))
}

# Example usage:
# Create a sample array (vector in R) of N numbers
my_numbers <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)

# Call the function to count even and odd numbers


counts <- count_even_odd(my_numbers)

# Print the results


print(paste("Number of even numbers:", counts$even))
print(paste("Number of odd numbers:", counts$odd))

# Another example with different numbers


another_set_of_numbers <- c(22, 33, 44, 55, 66, 77, 88)
another_counts <- count_even_odd(another_set_of_numbers)
print(paste("Number of even numbers (another set):", another_counts$even))
print(paste("Number of odd numbers (another set):", another_counts$odd))
recur_factorial <- function(n) {
if(n <= 1) {
return(1)
} else {
return(n * recur_factorial(n-1))
}
}

You might also like