0% found this document useful (0 votes)
10 views11 pages

Final409 (R)

The document outlines various classes of data analysis in R, including data frame creation, time series analysis, statistical tests, and data visualization techniques. It covers topics such as generating synthetic datasets, reading and processing Excel files, performing statistical tests like t-tests and ANOVA, and implementing ARIMA and SARIMA models for forecasting. Additionally, it discusses data manipulation using libraries like dplyr and ggplot2, and includes practical exercises with datasets like mtcars and airquality.
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)
10 views11 pages

Final409 (R)

The document outlines various classes of data analysis in R, including data frame creation, time series analysis, statistical tests, and data visualization techniques. It covers topics such as generating synthetic datasets, reading and processing Excel files, performing statistical tests like t-tests and ANOVA, and implementing ARIMA and SARIMA models for forecasting. Additionally, it discusses data manipulation using libraries like dplyr and ggplot2, and includes practical exercises with datasets like mtcars and airquality.
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

Class 1

[Link](123)

n <- 100

##making data frame

data<- [Link](
pregnant= sample(0:16,n, replace = TRUE),
glucose= pmax(round(rnorm(n, 120, 30)),50),
blood_pressure=pmax(round(rnorm(n,70,12)),40),
skin_thickness=pmax(round(rnorm(n,20,10)),0),
insulin= pmax(round(rnorm(n, 80, 40)),0),
bmi= pmax(round(rnorm(n, 30, 6),1),10),
pedigree= round(runif(n,0.1,2.5),3),
age=sample(21:64, n, replace=TRUE),
diabetes= sample(c("positive","negative"),n, replace=TRUE)
)
#sample=random pick , rnorm=normal distribution, runif=uniform decimals, round=value
rounding,

#pmax=lower bound value, pmin= upper bound

[Link](data,"C:/Users/Sayfa/Desktop/Sayfa/class/[Link]")

## after converting we use labels


a <- factor(data$diabetes,levels=c("positive","negative"),labels=c("yes","no"))
b <- cut(data$bmi, breaks = c(Inf,18.5,24.9,29.9,Inf),
labels=c("Under","Normal","Over","Obese"))
Class 2
library(readxl)
library(lubridate)
library(tseries)
data2 <- read_excel("C:/Users/Sayfa/Desktop/Sayfa/class/monthly_cloud_data.xlsx")
names(data2)
data2$Date<- ymd(data2$Date)

## Answer-1
ts_cloud<- ts(data2$Cloud_Oktas, start = c(2000,1), frequency = 12)
plot(ts_cloud, main= "Monthly Cloud Data (2000-2022)", ylab="Cloud Data", xlab="Year",
col="blue")

## Answer-2
mean(data2$Cloud_Oktas)
median(data2$Cloud_Oktas)
sd(data2$Cloud_Oktas)
hist(data2$Cloud_Oktas,main="Histogram Plot",xlab = "cloud_in_octas",ylab="frequency")

##Class Practise
BMD <- read_excel("C:/Users/Sayfa/Desktop/Sayfa/class/[Link]")
par(mfrow=c(2,2))

#Max-Temp
tmaxx <- ts(BMD$tmax, start = c(1981),frequency = 12)
plot(tmaxx, main= "Max Temp", ylab="temp", xlab="Year",col="red")

#Min-Temp
tminn <- ts(BMD$tmin, start = c(1981),frequency = 12)
plot(tminn, main= "Mini Temp", ylab="temp", xlab="Year",col="blue")

#Precipitation
rainfall <- ts(BMD$prcp, start = c(1981),frequency = 12)
plot(rainfall, main= "Rainfall", ylab="temp", xlab="Year",col="green")
Class 3
library(readxl)
monthly_cloud_data <-
read_excel("C:/Users/Sayfa/Desktop/Sayfa/class/monthly_cloud_data.xlsx")
data<- monthly_cloud_data

library(lubridate)
Date<- ymd(data$Date)

library(tidyverse)
library(dplyr)

##Filtering date

subset_data <- data%>%filter(Date>="2015-01-01" & Date<="2020-12-01")

ts_cloud<- ts(data2$Cloud_Oktas, start = c(2000,1), frequency = 12)


plot(ts_cloud, main= "Monthly Cloud Data (2000-2022)", ylab="Cloud Data", xlab="Year",
col="blue")

##PLot

ggplot(subset_data, aes(x=Date, y=Cloud_Oktas)) +


geom_line()+labs(title="Cloud Cover: 2015-2020", x="Date", y="Cloud")

##Decompose
decomposed<-decompose(ts_cloud)
plot(decomposed)

trend_part <- decomposed$trend


seasonal_part <- decomposed$seasonal
random_part <- decomposed$random
components_df <- [Link](Date = data$Date, observed=ts_cloud,
Trend=trend_part,seasonal= seasonal_part,
Random= random_part)
head(components_df)

[Link](data, "C:/Users/USER/Desktop/Sayfa/[Link]")
library(readxl)
rain_data <- read_excel("C:/Users/Sayfa/Desktop/Sayfa/class/[Link]")

library(lubridate)
library(dplyr)
library(ggplot2)

##Covert date style (separate to merge year and month)

rain_data<- rain_data%>%mutate(Date=make_date(year,mon))
tt<- ymd(rain_data$Date)
rain_data$Date<-ymd(rain_data$Date)

##RainfalPLot

ggplot(rain_data, aes(x=Date, y=prcp))+


geom_line(color="red")

##GGPLOT of Average of each year rainfall

annual_avg <- rain_data %>%


group_by(year) %>%
summarise(Average_Rainfall = mean(prcp, [Link] = TRUE))

##For each group created by group by(year), summaries() calculates the mean of prcp
(precipitation).

##Normal Plot
plot(annual_avg$year, annual_avg$Average_Rainfall, type = "o",
xlab = "Year", ylab = "Average Rainfall (mm)",
main = "Average Annual Rainfall", col = "blue")

ggplot(annual_avg, aes(x = year, y = Average_Rainfall)) +


geom_line(color = "blue") +
geom_point(color = "darkblue") +
labs(title = "Average Annual Rainfall",
x = "Year",
y = "Average Rainfall (mm)") +
theme_minimal()
Class 4
summary(mtcars$mpg) colnames(data)[c(2, 4)] <- c("cylinder",
names(mtcars) "horse-power")
head(mtcars)
data$Result<- data$`horse-power`/data$wt
#Mean names(data)
mean(mtcars$mpg)
hist(mtcars$mpg)
##Changing the level

#Median data$cylinder<- [Link](data$cylinder)


median(mtcars$mpg)
levels(data$cylinder)<-
#Mode c("low","moderate","high")
getmode<- function(v)
{
uniqv<- unique(v) ##Change to level creating new column
data$cylinder<- [Link](data$cylinder)
uniqv[[Link](tabulate(match(v,uniqv)))]
LEVEL <- c("low", "moderate", "high")
}
data$levCyl <- factor(data$cylinder, labels =
getmode(mtcars$cyl)
LEVEL)
getmode(mtcars$mpg)

##Variance and Standard Deviation #check frequency


a<- var(mtcars$mpg) table(mtcars$cyl)
b<- sqrt(a)
sd(mtcars$mpg)
##Range table
#BOX-plot
breaks <- c(-Inf, 15, 20, Inf)
boxplot(mtcars$mpg)
labels <- c("weak", "normal", "strong")
data$range_label <-
#Renaming the column cut(data$MilesPerGallon, breaks = breaks,
data<-mtcars labels = labels, right =
names(data) FALSE)
colnames(data)[1] <- "MilesPerGallon"
table(data$range_label)
Class 5
##Shapiro-Wilk normality test
[Link](mtcars$mpg)
data$am<- [Link](mtcars$am)

#W-statistic measures how close your data is to normal.


#p > 0.05 → Fail to reject the null hypothesis
#p ≤ 0.05 → Reject the null hypothesis

##T-test
[Link](mpg~am, data=mtcars)
##t = The test statistic. A more extreme value indicates
## stronger evidence against the null hypothesis.

library(readxl)
result <- read_excel("C:/Users/USER/Desktop/Sayfa/[Link]")
result$Group<-[Link](Result$Group)
[Link](Result~Group, data=result)

##Anova test
summary(aov(mpg~cyl,data=mtcars))

##Z-table
pnorm(1.96)
qnorm(0.975)
rnorm(17,3.80,0.123)

#binomial
pbinom()
rbinom(1000,5,0.5)

##Co-relation
cor(mtcars$mpg, mtcars$hp)

##Pearson's product-moment correlation


[Link](mtcars$mpg,mtcars$hp)
##Pearson's Chi-squared test
[Link](mtcars$cyl,mtcars$am)
##Regression

##linear model
model <- lm(mtcars$mpg~ mtcars$hp+mtcars$wt+mtcars$cyl, data=mtcars)
summary(model)

##Binary logistic
logit_model <- glm(mtcars$am ~ mtcars$hp + mtcars$mpg,
data = mtcars, family = binomial)
summary(logit_model)

##PLOT
par(mfrow=c(2,2))
plot(model)

Class 6
library(readxl)
BMD_data <- read_excel("C:/Users/Sayfa/Desktop/Sayfa/class/[Link]")

rain_ts<-ts(BMD_data$prcp, start = c(1981,1), frequency=12)


rain_ts
plot(rain_ts, main="Monthly Avg Rainfall",xlab="Year",ylab="Rainfall(mm)", col="brown")

## Dickey-Fuller Test
library(tseries)
[Link](rain_ts)

##1st Difference
rain_diff <- diff(rain_ts)
plot(rain_diff,main="First-order Difference")
[Link](rain_diff)

##2nd Difference
rain_diff2 <- diff(diff(rain_ts))
plot(rain_diff2, main = "Second-order Difference")
[Link](rain_diff2)

##Arima(Auto Regressive Integrated Moving Average) Model


library(forecast)
model_arima <- [Link](rain_ts)
summary(model_arima)

forecast_arima <- forecast(model_arima,h=24)


plot(forecast_arima)

Class 7
##SARIMA Model
##The forecast data is within 95% confidence interval

library(tseries)
library(forecast)

model_sarima <- [Link](rain_ts, seasonal = TRUE)


summary(model_sarima)
forecast_sarima <- forecast(model_sarima, h=60)
plot(forecast_sarima)

## If model of arima is given: order = c(p, d, q)


fit_sarima <- Arima(rain_ts, order = c(0,0,1), seasonal = c(1,1,0))
summary(fit_sarima)

##Model digonasis
checkresiduals(fit_sarima)

##No auto-correlation till 24 lag time. Statistically significant model.

spectrum(rain_ts) ## To identify dominant cycles or periodic patterns


## in a time series by analyzing frequency components.
spectrum(rain_ts,log = "no")

##Wavelet Analysis
library(WaveletComp)
data <- [Link](time=time(rain_ts), value=rain_ts)
wt <- [Link](data, [Link] = "value", [Link] = 0)
[Link](wt)
library(readxl)
rain <- read_excel("C:/Users/USER/Desktop/Sayfa/[Link]")
temp <- read_excel("C:/Users/USER/Desktop/Sayfa/[Link]")
combine <- merge( rain, temp, by = c("year"))
write_xlsx(combine,"C:/Users/USER/Desktop/Sayfa/[Link]" )

Class 8
#Making Data frame (Table)
Number <- 1:8
Diet <- c("Poor","Poor","Good","Good","Poor","Good","Poor","Good")
Sex <- c("M","F","M","F","F","F","M","M")
Weight <- c(156,180,167,190,177,183,154,160)
Morph <- c("Winged","Winged","Wingless","Intermediate",
"Winged","Intermediate","Winged","Wingless")
data <- [Link](Number, Diet, Sex, Weight, Morph)

##Add column
[Link] <- c(34,43,40,43,40,43,33,38)
data <- cbind(data, [Link])

##Add row
Newcommer <- c (9,"Poor","F",150,"Winged", 40)
data <- rbind(data, Newcommer)

##delete - array method


data3 <- data[ ,-4]
##deleting multiple column
data4 <- data[, -c(2, 4, 5)]

##Seprate data- subset


data2 <- subset(data, select = Weight)
##Seprate multiple data- subset
data2 <- subset(data, select = c(Weight, Sex))

##Changing column names


names(data$Diet) <- c("Dieeeeeet")

save(list = "data", file = "C:/Users/USER/Desktop/Sayfa/[Link]")


table(Sex)
class_data <- tibble(
name = c("X","Y","Z"), gender = c("M","F","F"), age = c(20,25,30),
Married = c(TRUE, FALSE, TRUE)
)
class_data

class_data2 <- tribble(


~name, ~sex, ~age,
"a", "F",30,
"b","M",45)
)

sayfa <- iris

library(tidyverse)
airquality <- [Link](airquality)

names(airquality)
small_dat <- select(airquality, Ozone:Wind)
head(small_dat)[1:4, ]

##Mean in monthly basis


summarize(month, oz=mean(Ozone, [Link]=T), solar=mean(Solar.R, [Link]=T))
mean(airquality$Ozone)
mean(airquality$Ozone)

Class 9
data <- airquality
View(data)

##corelation with missing data


cor(data$Ozone, data$Wind, use="[Link]")
mean(data$Ozone, [Link]=T)

##replace the missing data in column


data$Ozone[[Link](data$Ozone)] <- mean(data$Ozone, [Link] = TRUE)
View(data)
data$Ozone <- ifelse([Link](data$Ozone),
mean(data$Ozone, [Link] = T), data$Ozone)
##replace the missing whole data set
data[] <- lapply(data, function(x) {
if ([Link](x)) {
x[[Link](x)] <- mean(x, [Link]= T)
}
return(x)
})

You might also like