0% found this document useful (0 votes)
2 views18 pages

R Programing Lab

madras university syllabus
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)
2 views18 pages

R Programing Lab

madras university syllabus
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

Program 3: R And Databases

Note: first type the following in R console

[Link](“RSQLite”)

Data base connectivity: Program code:

library(DBI)

con<-dbConnect(RSQLite::SQLite(),":memory:")

dbListTables(con)

character(0)

dbWriteTable(con,"mtcars",mtcars)

dbListTables(con)

[1] "mtcars"

dbListFields(con,"mtcars")

[1] "mpg" "cyl" "disp" "hp" "drat" "wt" "qsec" "vs" "am" "gear"
[11] "carb"

dbReadTable(con,"mtcars")
res<-dbSendQuery(con,"SELECT * FROM mtcars WHERE cyl=4")

dbFetch(res)
Program 4: Dates
Program Code: Output:
# Basic Date format (YYYY-MM-DD)
today <- [Link]()
formatted_date <- [Link] ("2026-12-25")
print(formatted_date)

# Arithmetic with dates


days_remaining <- formatted_date - today
print(paste("Days until Christmas:", days_remaining))

# Using lubridate for easy extraction


library(lubridate)
year(today)
month(today)
day(today)

Program 5: Factors OUTPUT:


Program code:

# Create a vector of categories


sizes <- c("small", "large", "medium", "small", "large")

# Convert to a factor
size_factor <- factor(sizes, levels = c("small", "medium",
"large"))

print(size_factor)
levels(size_factor) # Shows the unique categories
table(size_factor) # Counts occurrences per category
Program 6: Subscribing
Program code:

subscribers <- list()


subscribe <- function(name, callback) {
subscribers[[name]] <<- callback
}
publish <- function(message) {
for (s in subscribers) {
s(message)
}
}
# Subscribers
subscribe("A", function(msg) cat("A received:", msg, "\n"))
subscribe("B", function(msg) cat("B received:", msg, "\n"))
# Publish message
publish("Hello Subscribers!")

output:
PROGRAM 7: Character Manipulation
Output:

Program code:
#1. Conversion to Upper Case
print(toupper(c("r","PROGramming")))
#[Link] to lower Case
print(tolower(c("LEARN R","HELLO")))
#[Link] CASEFOLD() FUNCTION
print(casefold(c("Learn R","hI")))
#USING CASEFOLD() FUNCTION with upper
print(casefold(c("Learn R","hI"),upper=TRUE))
#[Link] Replacement
chartr("a","A","An honest man gave that")
chartr("is","#@",c("This is it","It is great"))
#5. Splitting the String
strsplit("Welcome to R"," ")
#[Link] with Sub Strings
substr("learn Code in R",1,4)
#[Link] of character from a string
str<-c("program","with","a","new","language")
substr(str,3,3)<-c("%")
print(str)
PROGRAM 8: Data Aggregation
data=[Link](subjects=c("java","python","java","java","php","php"),

id=c(1,2,3,4,5,6),

names=c("Manoj","sai","mounika","devi","deepika","roshan"),

marks=c(89,89,76,89,90,67))

cat("\n Sample Data Frame\n")

print(data)

#[Link] THE SUM OF MARKS

cat("\n Aggregate Sum of marks with subjects\n")

print(aggregate(data$marks,list(data$subjects),FUN=sum))

#[Link] THE MINIMUM OF MARKS

cat("\n Aggregate minimum of marks with subjects\n")

print(aggregate(data$marks,list(data$subjects),FUN=min))

#[Link] THE MAXIMUM OF MARKS

cat("\n Aggregate maximum of marks with subjects\n")

print(aggregate(data$marks,list(data$subjects),FUN=max))

#[Link] MEAN OF MARKS

cat("\n Aggregate mean of marks with subjects\n")

print(aggregate(data$marks,list(data$subjects),FUN=mean))
OUTPUT:
PROGRAM 9: Reshaping Data Basics
Program 9(a).Transpose of the matrix
Program code:

first <- matrix(c(1:12),nrow=4,byrow=TRUE)


print("Original Matrix")
first
first<-t(first)
print("Transpose of the Matrix")
first
output:

Program 9(b).Joining rows and coloumns in data frame


Program code:

name<-c("shaoni","esha","soumitra","soumi")
age<-c(24,53,62,29)
address<-c("puducherry","kolkata","delhi","bangalore")
info<-cbind(name,age,address)
print("combining vectors into data frame using cbind")
print(info)

#to add new data

newd<-[Link](name=c("sounak","bhabani"),
age=c("28,87"),
address=c("bangalore","delhi"))
[Link]<-rbind(info,newd)
print("Combining data frames using rbind")
print([Link])
OUTPUT:

Program 9(c).Merging two data frames


Program code:

d1<-[Link](name=c("abi","ajay","sonu"),
id=c("111","112","113"))
d1
d2<-[Link](name=c("lovely","banu"),
id=c("114","115"))
d2
total<-merge(d1,d2,all=TRUE)
print(total)

OUTPUT:
PROGRAM 10: The R Enivironment
# creating a new environment
newEnv<-[Link]()
#Assigning variables
newEnv$x<-1
newEnv$y<-"GFG"
newEnv$z<-1:10
print(newEnv$z)

# creating bindings and environments


ls()

#print bindings of newEnv


ls(newEnv)
#list all the environment of the parent
search()

#removing newEnv
rm(newEnv)
ls()

OUTPUT:
PROGRAM 11: PROBABILITY AND DISTRIBUTIONS

Program 11(a).Discrete Probability distributions in R

Program code:

[Link] Distribution

random_binom<-rbinom(100,size=10,prob=0.5)

print(random_binom)

output:

[Link] Distribution

random_bern<-rbinom(100,size=1,prob=0.7)

print(random_bern)

OUTPUT:

[Link] Distribution
random_pois<-rpois(100,lambda=4)

print(random_pois)

OUTPUT:
4. Geometric Distribution

random_geom<-rgeom(100,prob=0.3)

print(random_geom)

OUTPUT:

5. Multinomial Distribution

random_multinom<-rmultinom(5,size=10,prob=c(0.2,0.3,0.5))

print(random_multinom)

OUTPUT:
Program 11(b).Continuous Probability distributions in R
Program code:
[Link] Distributions
random_norm<-rnorm(100,mean=0,sd=1)
print(random_norm)

OUTPUT:

[Link] Distributions
random_unif<-runif(100,min=0,max=10)
print(random_unif)

OUTPUT:

[Link] Distribution

random_exp<-rexp(100,rate=0.2)
print(random_exp)
OUTPUT:

[Link]-Square Distribution

random_chisq<-rchisq(100,df=5)
print(random_chisq)

OUTPUT:
PROGRAM 12: DESCRIPTIVE STATISTICS AND GRAPHICS
Program 12(a).Descriptive Statistics

[Link] the data:


data(iris)

df<-iris

print(df)

output:

2. finding minimum and maximum values:

cat("Minimum Sepal Length:",min(df$[Link]),"\n")

cat("Maximum Sepal Length:",max(df$[Link]),"\n")

output:
3. calculation of mean ,median and Quartiles:

cat("Mean of Sepal Length:",mean(df$[Link]),"\n")

cat("Median of Sepal Length:",median(df$[Link]),"\n")

cat("1st quartile of Sepal Length:",quantile(df$[Link],0.25),"\n")

cat("3rd quartile of Sepal Length:",quantile(df$[Link],0.75),"\n")

cat("Interquantile of Sepal Length:",IQR(df$[Link]),"\n")

output:

4. standard deviation and variance:

cat("Standard Deviation of Sepal Length:",sd(df$[Link]),"\n")

cat("Variance of Sepal Length:",var(df$[Link]),"\n")

output:

5. grouping By Species

by(df,df$Species,summary)

output:
Program 12(b).Graphical Descriptive Statics in R
(a) Histogram:
Program code:
hist(df$[Link],
main="Histogram of Sepal Length",
xlab="Sepal Length(cm)",
ylab="Frequency",
col="lightblue",
border="black",
breaks=10)
OUTPUT:

(b) Boxplot:
Program code:
boxplot([Link]~ Species,data=df,
main="Box Plot of Sepal Length by Species",
xlab="Species",
ylab="Sepal Length(cm)",
col=c("lightblue","lightgreen","lightpink"),
notch=FALSE,
horizontal=FALSE)
OUTPUT:
(c) Scatter Plot:
Program code:
plot(df$[Link],df$[Link],
main="Scatter Plot of Sepal Length vs Petal Length",
xlab="Sepal Length(cm)",
ylab="petal Length(cm)",
pch=20,
col="Purple",
cex=1.5,)
OUTPUT:

You might also like