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

R Programs 2024-2025

The document contains a series of R programming examples demonstrating various data manipulation and analysis techniques. Key programs include generating Fibonacci numbers, finding maximum and minimum values in a vector, identifying prime numbers, and creating visualizations with ggplot2. Additional examples cover data organization, geographic data analysis, and performing calculations on datasets.

Uploaded by

I56 Ganesh G
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)
40 views13 pages

R Programs 2024-2025

The document contains a series of R programming examples demonstrating various data manipulation and analysis techniques. Key programs include generating Fibonacci numbers, finding maximum and minimum values in a vector, identifying prime numbers, and creating visualizations with ggplot2. Additional examples cover data organization, geographic data analysis, and performing calculations on datasets.

Uploaded by

I56 Ganesh G
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/ 13

Program 1: Write a R program to get the first 10 Fibonacci numbers.

print_fibonacci <- function(n) {


a <- 0
b <- 1
cat("Fibonacci Sequence:")
for (i in 1:n) {
cat(a, " ")
next_num <- a + b
a <- b
b <- next_num
}
}
# Example usage
number_of_terms <- 10
print_fibonacci(number_of_terms)
Output:
Fibonacci Sequence:0 1 1 2 3 5 8 13 21 34

Program 2: Write a R program to find the maximum and the minimum value of a given
vector.
x = c(10, 20, 30, 25, 9, 26)
print("Original Vectors:")
print(x)
print("Maximum value of the above Vector:")
print(max(x))
print("Minimum value of the above Vector:")
print(min(x))
Output:
Program 3: Write a R program to get all prime numbers up to a given number.
N <- 25
# Function to check if a number is prime
is_prime <- function(num) {
if (num <= 1) {
return(FALSE)
}
for (i in 2:sqrt(num)) {
if (num %% i == 0) {
return(FALSE)
}
}
return(TRUE)
}
# Generate and print prime numbers up to N
cat("Prime numbers up to", N, "are:\n")
for (i in 2:N) {
if (is_prime(i)) {
cat(i, " ")
}
}
Output:
3 5 7 11 13 17 19 23

Program 4: Write a R program to get the unique elements of a given string and unique
numbers of vector
str1 = "The quick brown fox jumps over the lazy dog."
print("Original vector(string)")
print(str1)
print("Unique elements of the said vector:")
print(unique(tolower(str1)))
nums = c(1, 2, 2, 3, 4, 4, 5, 6)
print("Original vector(number)")
print(nums)
print("Unique elements of the said vector:")
print(unique(nums))
Output:
Program 5: Two Categorical Variables – Discover relationships within a dataset
data(mtcars)
head(mtcars)
install.packages("ggplot2")
library(ggplot2)
"cyl" and "gear"

ggplot(data = mtcars, aes(x = factor(cyl), fill =


factor(gear))) +
geom_bar(position = "stack", color = "black") +
labs(title = "Relationship between Cylinder Count and Gear
Type",
x = "Number of Cylinders",
y = "Count",
fill = "Gear Type") +
theme_minimal()
Program 6: Create Two Dimensional Tables from Multi-Dimensional Cross-Tabulations
# Create a sample dataset
data <- data.frame(
gender = c("Male", "Male", "Female", "Female", "Male", "Female"),
agegroup = c("18-30", "31-40", "41-50", "18-30", "31-40", "41-
50"),
employmentstatus = c("Employed", "Unemployed", "Employed",
"Employed","Unemployed","Unemployed"),
stringsAsFactors = FALSE
)

# Perform a multi-dimensional cross-tabulation and print


cross_tab <- table(data$gender, data$agegroup,
data$employmentstatus)
print(cross_tab)

# Create a two-dimensional table for a specific dimension


# For example, Gender vs EmploymentStatus
gender_vs_employment <- margin.table(cross_tab,c(1,3))
print(gender_vs_employment)

age_vs_employment <-margin.table(cross_tab,c(2,3))
print(age_vs_employment)

Output:
Program 7:
install.packages(c("ggplot2", "ggpubr", "tidyverse", "broom",
"AICcmodavg"))

library(ggplot2)
library(ggpubr)
library(tidyverse)
library(broom)
library(AICcmodavg)
crop.data <- read.csv("F:/crop.yield.csv", header = TRUE, colClasses
= c("factor","factor","factor", "factor","factor", "numeric"))
summary(crop.data)

one.way <- aov(Yield ~ Temperature.at.2.Meters..C., data =


crop.data)
summary(one.way)
Output:

Program 8: Fit a simple linear regression model using the lm() function.

df <- data.frame(x=c(1,2,3,4,5),
y=c(1,5,8,15,26))
linear_model <- lm(y~x^2, data=df)
summary(linear_model)
Output:
Program 9: Program Experiment the steps to connect with a data source and choose between
live connection and extract using R

1.CSV Files:
data <- read.csv("path/to/your/file.csv")

2.Excel Files:
library(readxl)
data <- read_excel("path/to/your/file.xlsx")

3.Database (e.g., MySQL, PostgreSQL):


library(RMySQL)
con <- dbConnect(MySQL(),
user="username",
password="password",
dbname="database_name",
host="host_address")
data <- dbGetQuery(con, "SELECT * FROM your_table")
dbDisconnect(con)

4. Google Sheets:
library(googlesheets4)
gs4_auth()
Program 10: Program to Add Web Images Dynamically to Worksheets using R

Program 11: Program to Organize and Customize Fields in the Data Pane. using R
library(dplyr)
library(tidyr)
data<-data.frame(
ID=1:5,
Name=c("John", "Alice", "Bob", "Emily", "David"),
Age = c(25, 30, 35, 40, 45),
City = c("New York", "Los Angeles", "Chicago", "Houston","Miami"),
Income = c(50000, 60000, 70000, 80000, 90000)
)
print("Original Dataset:")
print(data)

organized_data<-data%>%
select(ID, Name, Age, Income, City)

organized_data <- organized_data %>%


select(Person_name= Name, Annual_Income=Income)

print("Organized Dataset:")
print(organized_data)

Output:

Program 12: Perform Maps and Geographic Data Analysis using data analytics R

install.packages("ggplot2")
install.packages("sf")
install.packages("dplyr")
install.packages("leaflet")

library(ggplot2)
library(sf)
library(dplyr)
library(leaflet)

shapefile <- st_read("F:/7th Sem/R/australia/web/map/map.shp")

st_crs(shapefile)

shapefile <- st_transform(shapefile, crs = 4326)

st_crs(shapefile)

ggplot() +
geom_sf(data = shapefile)

ggplot() +
geom_sf(data = shapefile, fill = "lightblue", color = "black") +
labs(title = "Your Map Title", subtitle = "Your Map Subtitle",
caption = "Your Map Caption") +
theme_minimal()

centroids <- st_centroid(shapefile)

centroid_coords <- st_coordinates(centroids)


centroids <- cbind(centroids, centroid_coords)

ggplot() +
geom_sf(data = shapefile, fill = "lightblue", color = "black") +
geom_point(data = centroids, aes(x = X, y = Y), color = "red") +
labs(title = "Map with Centroids")

leaflet() %>%
addProviderTiles("Stamen.TonerLite") %>%
addPolygons(data = shapefile, fillOpacity = 0.5, color = "black")

Output:

Program 13: Perform quick table calculations including creating


calculated fields, calculating moving averages, and computing
percentages of the total.

# Load the dplyr package


install.packages("zoo")
library(zoo)
library(dplyr)

# Sample data
data <- data.frame(
ID = c(1, 2, 3, 4),
Sales = c(100, 200, 150, 300),
Cost = c(50, 80, 60, 120)
)

# Creating a calculated field for Profit


data <- data %>%
mutate(Profit = Sales - Cost)

print(data)

# Calculating 3-period moving averages for Sales


data <- data %>%
mutate(Moving_Average_Sales = zoo::rollmean(Sales, k = 3, fill =
NA))

print(data)

# Computing percentages of the total for Sales and Cost


data <- data %>%
mutate(
Sales_Percentage = Sales / sum(Sales) * 100,
Cost_Percentage = Cost / sum(Cost) * 100
)

print(data)

Output:
Program 14: Write a program to apply filters to dimensions and measures
library(dplyr)

data<-data.frame(
product =c('A','B','C','D'),
sales =c(100,200,150,300),
cost=c(50,80,60,120)
)

cat("Original data:\n")
print(data)

filtered_data <-data%>%
filter(sales>150)

cat("\nFiltered Data(Sales>150):\n")
print(filtered_data)

Output:
Program 15:
# Install and load necessary libraries
install.packages("sf") # Install sf package if you don't have
it
library(ggplot2)
library(sf)
library(dplyr)

# Load the shapefile for Indian states (make sure to change


the file path)
india_states_shapefile <- st_read("F:/7th
Sem/R/StatPlanet_India_Hindi/map/map.shp") # Specify the
correct path to the shapefile

# Sample data (population of Indian states)


state_data <- data.frame(
State = c("Andhra Pradesh", "Arunachal Pradesh", "Assam",
"Bihar", "Chhattisgarh"),
Population = c(49506799, 1383727, 31205576, 104099452,
25540196)
)

# Merge the shapefile with the population data by state name


# Make sure the names match the shapefile's attribute column
for state names
merged_data <- india_states_shapefile %>%
left_join(state_data, by = c("NAME_1" = "State")) #
"NAME_1" is the typical column for state names in shapefiles

# Check merged data to ensure population values are added


head(merged_data)

# Plotting the map


ggplot(merged_data) +
geom_sf(aes(fill = Population)) +
scale_fill_gradient(low = "lightblue", high = "darkblue",
name = "Population") +
labs(title = "Population Distribution of Indian States") +
theme_minimal()
Output:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy