######################################
#####jalase 1##########
######################################

### sakhte bordar  eshare  be mohtaviyatash ### 
x<-c(2,5,6)
x
x[2]
y<-1:1000
y
length(y)
n<-seq(1,2000,2)
n
seq(0,1,l=1000)
rep(5,10)
rep(c(2,3,4),10)
rep(c(2,3,4),each=10)
rep(c(2,3,4),c(5,7,10))2

### sakhte matrix ###
A<-matrix(c(4,5,10,20),nrow=2,ncol=2)
A
A<-matrix(c(4,5,10,20),nrow=2,ncol=2,byrow=T)
A
B<-matrix(0,5,5)
B
A[2,1]
C<-matrix(1:9,3,3)
C
C[2,3]
C[3,3]<-10
C
C[,-2]
C[2:3,2:3]

### tamrin: yek bordare harfi besazim ###
### tamrinaye akhare fasle ketab hal shavad ###

################################
### jalase2 ###
###############################

?diag
diag(5)
x<-c(2,4,6,8,10)
diag(x)
A<-matrix(1:9,3)
A
diag(A)
B<-matrix(10:21,3,4)
B
cbind(A,B)
rbind(A,B)
C<-matrix(10:21,4,3)
C
rbind(A,C)
dim(A)
dim(B)
?array

array(c(1:8,11:18,111:118),dim=c(2,4,3)) ### matrise chand bodi ###

?list ### harchizi mitavanad begirad (bedune charchub va bedune nazm)###

list(x,A,B,C,c("ali","reza","mohammad","ahmad"))

list(x=x,A=A,B=B,C=C,z=c("ali","reza","mohammad","ahmad"))

data1<-list(x=x,A=A,B=B,C=C,z=c("ali","reza","mohammad","ahmad"))
data1

### tamrin :ye list az nomart darshamon dar termhaye mokhtalef besazim ###

data1$z["mohammad"]
data1$z$3
data1[[5]]   
data1[[5]][3]
M<-matrix(c(60,50,70,50,90,95),3,2)
M
p<-list(c("ali","reza","hasan"),c("stat","math"))
p
dimnames(M)<-p
M
M[,"stat"]
X1<-matrix(c("reza",10,12,15),2)
mean(X1[-1,1])
mean(X1[,2])
?data.frame
stat<-c(60,50,70)
math<-c(50,90,95)
Name<-c("ali","reza","hasan")
data2<-data.frame(Name,math,stat,S=c(TRUE,FALSE,TRUE))

### tamrin: yek dataframe az nomrehaye darshameyan dar termhaye ghabli ###

data2
data2[,1]
data2$Name
data2[,"Name"]

is.factor(data2[,1]) ### aya factor ast? ###
is.vector(data2[,1])

##########################################################
### jalae3 ###
##########################################################

?mode
x<-1:4
mode(x)
y<-c("reza","ali")
mode(y)
z<-c(TRUE,FALSE)
mode(z)
v<-c(.1,.2)
mode(v)

################
x<-1:10
x
is.matrix(x)
is.vector(x)
x<-as.matrix(x)
is.matrix(x)
is.vector(x)
x<-as.list(x)
is.matrix(x)
is.vector(x)
is.list(x)

#############

?read.table
read.table("data.xlsx",header=TRUE)
read.table("data1.txt",header=TRUE)
read.table("data1.txt",header=FALSE)
read.table("data2.txt",header=TRUE,sep=",")
scan("data2.txt",header=TRUE,sep=",")
x<-scan("data2.txt",sep=",")
x
?na.omit
y<-na.omit(x)
y
as.numeric(y)
read.csv("data3.csv",header=TRUE)

######################################

d<-file.choose()
d
read.csv(d,header=TRUE)
getwd()
setwd("C:/Users/AS/Desktop/mohasebat97")
?write.table
x<-data.frame(Name=c("ali","reza"),nomre=c(10,15))
write.table(x,file="nomre.txt")
write.csv(x,file="nomre.csv")


##########################################################
### jalase4 ###
##########################################################

dnorm(0)
pnorm(0) ### tabee tozi
qnorm(.07) ### ehtemale x haye kamtar az -1.47 mishavad 0.07
x<-
?distribution
1-pchisq(1,3)

######################
### fasle 4 ###
######################

### usule barnamenevisi ###

z<-1
if(z==0) y=1 else y=0
y
z<-0
if(z==0) y=1 else y=0
y 


x<-c(1,2,3,-1,-2)
all(x>0)


y<-0
for(i in 1:5){
y[i]<-any(x[i]==x[-i])
}
y
any(y)


x<-c(1,2,3,-1,2)
y<-0
for(i in 1:5){
y[i]<-any(x[i]==x[-i])
}
y
any(y)

### barnamei benevisid ke yek adade chand raghami ro begire be ma bege k in adad bar 2,3 bakhshpazir hast ya nist , aya adad aval hast ya nist###

### barnamei benevisid k se adad ro begire beonvan tul azlae yek mosalas###

### for while va repeat ###

#######################################
### jalase 5 ###
#######################################

### tabei benevisid k yek adade sahih ro begire va be ma teded rgham haye an ra bedahad

### tabei benevisid k yek matris ra begirad va jame satr  va sutun hara be surate yek be ma bedahad

A<-matrix(1:9,3)
A
d<-dim(A)
# d[1]
#d[2]
r<-0
for(i in 1:d[1]) r[i]<-sum(A[i,])
r
c<-0
for(j in 1:d[2]) c[j]<-sum(A[,j])
c
list(sumrow=r,sumcol=c)

###

sum_matrix<-function(A=matrix(0)){
if(is.matrix(A)){
d<-dim(A)
r<-0
for(i in 1:d[1]) r[i]<-sum(A[i,])
c<-0
for(j in 1:d[2]) c[j]<-sum(A[,j])
return(list(sumrow=r,sumcol=c))
} else print("please input a matrix")
}
sum_matrix
B<-matrix(1:15,3,5)
B
sum_matrix(B)
sum_matrix(5)
sum_matrix(c(1,4,5))
sum_matrix()

################
### mesale 2
r<-0
x=5990
while(x>0){
x<-x%/%10
r<-r+1
}
r

#######################################
### jalase 6 ###
#######################################

###rasme tabe chegali normal ba estefade az curve#####

curve((2*pi)^(-0.5)*exp(-x^2/2),-4,4)
curve(dnorm(x,0,1),-4,4,col=2,lty=2,add=T)
curve(dnorm(x,0,2),-4,4,col=3,lty=3,add=T)
curve(dnorm(x,0,0.5),-4,4,col=4,lty=4,add=T)

###############

curve(dnorm(x,0,1),-4,4,ylim=c(0,0.8))
curve(dnorm(x,0,2),-4,4,col=2,lty=2,add=T)
curve(dnorm(x,0,0.5),-4,4,col=3,lty=3,add=T,lwd=2)
curve(dt(x,df=1),-4,4,col=4,lty=4,add=T)
curve(dt(x,df=2),-4,4,col=4,lty=4,add=T)
curve(dt(x,df=10),-4,4,col=4,lty=4,add=T)
curve(dt(x,df=30),-4,4,col=6,lty=4,add=T)

###########

curve(dnorm(x,0,1),-4,4,ylim=c(0,0.8))
curve(dnorm(x,0,2),-4,4,col=2,lty=2,add=T)
curve(dnorm(x,0,0.5),-4,4,col=3,lty=3,add=T)
curve(dt(x,df=1),-4,4,col=4,lty=4,add=T)
#?legend
legend("topleft",legend=c("N(0,1)","N(0,2)","N(0,0.5)","t(1)"),col=1:4,lty=1:4, bg = "gray70")
legend("topleft",legend=c("N(0,1)","N(0,2)","N(0,0.5)","t(1)"),col=1:4,lty=1:4, bg = "antiquewhite2")
?rgb
rgb(0.5,0.5,1)
legend("topleft",legend=c("N(0,1)","N(0,2)","N(0,0.5)","t(1)"),col=1:4,lty=1:4, bg = rgb(0.5,0.5,1,0.5))

################################
###nemodar hae khas#######

x<-rnorm(30)
hist(x,col=rgb(1,0.5,0.5,0.9))
D<-hist(x,plot=F)
D
?hist
hist(x,col=rgb(1,0.5,0.5,0.9),breaks=c(-3,-1,1,3))

#########################################################
########jalase 7##########
###edame jalase ghabl####

##tamrin## rasme nemodar ba estefade az plot v lines##
x<-seq(-4,4,l=50)
x
y<-dnorm(x,0,1)
y
plot(x,y,type="p")
plot(x,y,type="l")
plot(x,y,type="b")
plot(x,y,type="o")
plot(x,y,type="n")
plot(x,y,type="s")
plot(x,y,type="h")
?plot
plot(x,y,type="S")
plot(x,y,type="c")

#############

plot(x,y,type="p")
lines(x,y,type="l",col=2)
lines(x,y,type="b",col=3)
lines(x,y,type="o",col=4)
lines(x,y,type="n")
lines(x,y,type="s",col=5)
lines(x,y,type="h",col=6)
lines(x,y,type="S",col=7)
lines(x,y,type="c",col=8)
rang<-colors()
rang[1]
rang[500]
plot(x,y)
lines(x,y,type="s",col=rang[500])
lines(x,y,type="h",col=rang[400])
lines(x,y,type="S",col=rang[300])
lines(x,y,type="c",col=rang[200])

##################

x<-seq(-4,4,l=200)
y<-dnorm(x,0,1)
plot(x,y,type="l",xlim=c(-5,5),ylim=c(0,1))
lines(x,dnorm(x,0,0.5),lty=2,col=2)
lines(x,dnorm(x,0,2),lty=3,col=rang[100])

#############
##tamrin###

x<-seq(0,15*pi,l=100)
y<-x*sin(x)
plot(x,y,type="l")
x<-seq(0,15*pi,l=100)
y<-x*cos(x)
lines(x,y,lty=2,col=2)
legend("topleft",legend=c("xsin(x)","xcos(x)"),col=1:2,lty=1:2, bg = "gray80")

################
####boxplot####

x<-rnorm(30)
y<-rt(30,df=2)
z<-rchisq(30,df=2)
boxplot(x)
B<-boxplot(x,plot=F)
B
boxplot(x,col=3,horizontal=T,notch=T)
?boxplot
boxplot(x,y,z,col=2:4,names=c("normal","t-student","chisquar"))

################
###nemodar milei###

x<-rbinom(100,10,0.5)
x
table(x)
barplot(table(x),col=2,main="barplot")
pie(table(x),col=2:8)

##################
#########################################################
########jalase 8##########

#######ravesh haye amari#####

?t.test

##example 1 page122##

x<-c(52,35,24,47,36,51,34,38,46,33,47,36,38,50,47,34,41,40,42,40,26,29,30,32,30,35,37,37,41,21,31,30,26,35,45,23,43,31,34,43)
#a) baresei normaliti 
par(mfrow=c(1,3))
hist(x,freq=F)
lines(density(x),col=2,lty=2)
boxplot(x)
qqnorm(x)
qqline(x)
shapiro.test(x)
#b)
y<-sample(x,7) 
y
par(mfrow=c(1,3))
hist(y,freq=F)
lines(density(y),col=2,lty=2)
boxplot(y)
qqnorm(y)
qqline(y)
shapiro.test(y)
#c) H0:mu=45 vs H1:mu>45
t.test(x,mu=45,alt="g")
#H0:mu=45 vs H1:mu!=45
t.test(x,mu=45,alt="t")
t.test(x,mu=45,alt="t",conf.level=0.99)

###mesale 3 page 130###

x<-c(70,71,74,69,73,50,59,85,68,45)

#########################################################
########jalase 9##########

####edame mesale 3#####
rm(list=ls())
ls()
x<-c(70,71,74,69,73,50,59,85,68,45)
#H0:mu=55  vs  H1:mu<55
qqnorm(x)
qqline(x)
shapiro.test(x)
ks.test(x,"pnorm",mean(x),sd(x))
scale(x)
mean(x)
sd(x)
ks.test(scale(x),"pnorm")
t.test(x,mu=55,alt="l",conf.level=0.95)
t.test(x,mu=55,alt="t",conf.level=0.95)

###azmon naparametri###

?wilcox.test
wilcox.test(x,mu=55,alt="l",conf.level=0.95,conf.int=T)

#####mesal 4 page 133######

#x uonje taze
#y uonje khoshk
x<-c(52,44,45,51,49,41,47,46,35,49,53,57,38,47,46,56,44,44)
y<-c(42,33,28,37,31,42,39,51,48,41,32,39,40,29,42,47,35)
#H:mux=muy  vs  H1:mux>muy
#mostaghel hastan nemone haye jamee
qqnorm(x)
qqline(x)
shapiro.test(x)
qqnorm(y)
qqline(y)
shapiro.test(y)
var.test(x,y)
?var.test
ansari.test(x,y)
mood.test(x,y)
t.test(x,y,alt="g",var.equal=T,paired=F)

####mesal 5 page136####

#x 1387
#y 1388
x<-c(544,703,653,311,464,513,293,721,392,427,433,209,489,378)
y<-c(557,687,639,338,507,533,307,717,374,449,482,228,506,421)
#H0:mux=muy vs H1:mux!=muy
#vabaste hastan nemone ha
qqnorm(x)
qqline(x)
shapiro.test(x)
qqnorm(y)
qqline(y)
shapiro.test(y)
t.test(x,y,alt="t",paired=T)

####################
#########################################################
########jalase 10##########

####### tarh azmayesh ha #####

####### one-way ANOVA ########

s1 <- c(66,65.5,66,65.5,66.5,67)
s2 <- c(64.5,65,64,65,64.5,64.5,64,65)
s3 <- c(65.5,65,64.5,66,64.5,65.5)
boxplot(s1,s2,s3 , names = c("sigar1","sigar2","sigar3"), col = c(4,2,3))
summary(s1)
summary(s2)
summary(s3)
a <- rep(c(1, 2, 3), c(6,8,6))
a
a <- factor(a, labels = c("s1","s2","s3"))
a
is.factor(a)# note: moteghayer haye keifi dar model hay amari bayad az noe factor bashand
data.s <- data.frame(y = c(s1,s2,s3), a = a )
data.s
boxplot(y~ a , data = data.s)
ggplot2::qplot(a, y ,data = data.s , geom = "point", color = a, shape = a)
ggplot2::qplot(a, y ,data = data.s , geom = "boxplot", color = a)
ggplot2::qplot(y ,data = data.s , geom = "histogram" , fill = a)
ggplot2::qplot(y ,data = data.s , geom = "density" , fill = a , alpha = 0.5)
?plot.design
plot.design(y ~ a, data = data.s)
M <- aov(y ~ a, data = data.s)
M
anova(M)

summary(M)
##### barresie sharayete model ####

## resid normality
R = resid(M)
qqnorm(R)
qqline(R)
shapiro.test(R)
## sobat variance
plot(fitted(M), R )
?var.test
# parametric
bartlett.test(y ~ a, data = data.s)
# non-parametric
fligner.test(y ~ a, data = data.s)
car::leveneTest(y ~ a, data = data.s)
## nahambastegie residual
ts.plot(R)
points(R)
abline(h = 0, lty = 2 , col = 2)
lmtest::dwtest(M)

####### moghayesat zoji #######

?TukeyHSD
TukeyHSD(M)
plot(TukeyHSD(M))

library(agricolae)
?LSD.test
?duncan.test
?SNK.test

#####################################
#####jalase 11#########

###tarh tak ameli####

###azmon naparametri###

?kruskal.test
kruskal.test(y~a,data=data.s)

###azmone tarh do ameli###

###example  2 page187##

#be onvane tamrin
data()
ToothGrowth
?ToothGrowth
len<-ToothGrowth$len
supp<-ToothGrowth$supp
dose<-ToothGrowth$dose
table(supp,dose)
table(supp)
table(dose)
is.factor(supp)
is.factor(dose)
dose<-as.factor(dose)
dose
boxplot(len~supp)
boxplot(len~dose)
boxplot(len~supp+dose)
plot.design(len ~supp)
plot.design(len ~dose)
plot.design(len ~supp+dose)
interaction.plot(supp,dose,len)
interaction.plot(dose,supp,len)
M<-aov(len~supp+dose+supp*dose)
M
anova(M)
summary(M)
coef(M)
model.tables(M)
TukeyHSD(M)
plot(TukeyHSD(M))
?aggregate
aggregate(len~supp,FUN="mean")
aggregate(len~dose,FUN="mean")
aggregate(len~supp*dose,FUN="mean")

#monasebat model

## resid normality

R = resid(M)
qqnorm(R)
qqline(R)
shapiro.test(R)

## sobat variance

plot(fitted(M), R )

# parametric

bartlett.test(R ~supp)
bartlett.test(R ~dose)

# non-parametric

fligner.test(R ~ supp )
fligner.test(R ~ fitted(M) )

car::leveneTest(R ~supp)

## nahambastegie residual

ts.plot(R)
points(R)
abline(h = 0, lty = 2 , col = 2)
lmtest::dwtest(M)

##################################################
#########jalase 12##########
###time series####
xt<-c(8,9,12,15,25,30,32,33,20,25,18,10,7,10,11,14,26,28,33,32,22,26,17,9)
xt
length(xt)
yt<-ts(xt)
yt
plot(yt)
yt<-ts(xt,start=c(2010,1),end=c(2012,12),freq=12)
yt
plot(yt)
####
data(AirPassengers)
AP<-AirPassengers
AP
plot(AP)
is.ts(AP)
?stl
fit1 <- stl(yt, s.window="period")
fit1
plot(fit1)
fit2 <- stl(AP, s.window="period")
fit2
plot(fit2)
library(forecast)
?ets
?HoltWinters
########################
###jalase13###
##edame jalase ghabl##
#HoltWinters

m1<-HoltWinters(yt,seasonal = "additive")
m1
plot(m1)
m2<-HoltWinters(yt,seasonal = "multiplicative")
m2
plot(m2)
par(mfrow=c(1,2))
plot(m1,main="m1")
plot(m2,main="m2")
names(m1)
m1$SSE
m2$SSE
m1$fitted
sum((yt-(m1$fitted)[,1])^2)
sum((yt-(m2$fitted)[,1])^2)
################
m3<-HoltWinters(AP,seasonal = "additive")
m3
m4<-HoltWinters(AP,seasonal = "multiplicative")
m4
par(mfrow=c(1,2))
plot(m3,main="m3")
plot(m4,main="m4")
m3$SSE
m4$SSE
################
library(forecast)
?forecast
f1<-forecast(m1,h=2*12)
plot(f1)
f2<-forecast(m4,h=5*12)
plot(f2)
####################
##ARIMA##
layout(matrix(c(1,2,1,3),2))
plot(yt)
plot(m1)
plot(m2)

layout(matrix(c(1,2,3,2),2))
plot(m1)
plot(yt)
plot(m2)
########################################
############jalase14###############
?arima
layout(matrix(c(1,2),2))
acf(yt,lag.max=10,type='cor',main='ACF')
acf(yt,lag.max=10,type='par',main='PACF')
## fitting arima model in R with library(forecast)
#model1=ar(1)
fit1=arima(yt, order=c(1,0,0))
fit1
fit2=arima(yt, order=c(2,0,0))
fit2
fit3=arima(yt, order=c(3,0,0))
fit3
summary(fit3)
fit4=arima(yt, order=c(3,0,1))
summary(fit4)
fit5=arima(yt, order=c(3,0,2))
summary(fit5)
fit6=arima(yt, order=c(3,0,3))
summary(fit6)
fit7<-auto.arima(yt)
summary(fit7)
yt1<-diff(yt,lag=12)
plot(yt1)
fit8=arima(yt1, order=c(0,0,1))
summary(fit8)
fit9=arima(yt, order=c(0,0,1),seasonal=c(0,1,0))
summary(fit9)
fit10=arima(yt, order=c(0,0,1),seasonal=c(0,1,3))
summary(fit10)
f1<-forecast(fit7,h=2*12)
f2<-forecast(fit10,h=2*12)
layout(matrix(c(1,2),2))
plot(f1)
plot(f2)
############
layout(matrix(c(1,2,1,3),2))
plot(AP)
acf(AP,type='cor',main='ACF')
acf(AP,type='par',main='PACF')
AP1<-diff(AP,1)
plot(AP1)
AP2<-diff(AP1,12)
plot(AP2)
layout(matrix(c(1,2,1,3),2))
plot(AP2)
acf(AP2,type='cor',main='ACF')
acf(AP2,type='par',main='PACF')
auto.arima(AP)
auto.arima(AP2)
## fitting arima model in R with library(forecast)
#model1=ar(1)
fit1=arima(AP, order=c(2,1,1),seasonal=c(0,1,0))
summary(fit1)

fit2=arima(AP, order=c(2,0,0))
fit2
fit3=arima(AP, order=c(3,0,0))
fit3
summary(fit3)
########################################
##### jalaseye 15 ###############
##### mohasebat #################
##### doreye jalasate ghabl #####
setwd("C:/Users/AS/Desktop/mohasebat97")
practice <- read.csv("practice_data.csv", header = TRUE)
X1 <- practice$X1
##################################
##### competition 7 ##############
getwd()
setwd("C:/Users/AS/Desktop/mohasebat97/Competition 7")
data7 <- read.csv("data7.csv", header = TRUE)
head(data7)
BMI = data7$WEIGHT / (data7$HEIGHT/100) ^ 2
BMI 
?cut
BMI1 <- cut(BMI,breaks = c(0 , 25 , 29.99 , max(BMI)+ 1))
BMI1 <- factor(BMI1, label = c("normal",  "over weight", "fat"))
BMI1 
length(BMI1)
length(data7$HTN)

data7$SEX
table(data7$HTN, data7$SEX)
# azmune nesbat
x1 = 18 
x2 = 35
n1 = 51
n2 = 49
prop.test(c(x1 ,x2 ), c(n1,n2))
# chi square test
chisq.test(table(data7$HTN, data7$SEX))
chisq.test(table(data7$HTN, data7$EDUCATION))
chisq.test(table(data7$HTN, BMI1))
# glm
# hame moteghayer 
is.factor(data7$SEX)
is.factor(data7$EDUCATION)
SEX <- factor(data7$SEX)
EDU <- factor(data7$EDUCATION)
HTN <- factor(data7$HTN)
SEX
EDU
HTN
length(SEX)
length(HTN)
length(EDU)
?glm
M <- glm(HTN~ SEX + BMI1 + EDU , family = binomial(link = "logit"))
M
summary(M)
coef(M)
#odds Ratio
OR<-exp(coef(M))
OR
1/OR
?relevel
########
sex1<-relevel(SEX,ref="2")
sex1
M1 <- glm(HTN~ sex1 + BMI1 + EDU , family = binomial(link = "logit"))
summary(M1)
OR<-exp(coef(M1))
OR
1/OR
#conf interval odd Ratio
exp(confint(M))

### AUTO RATIO yadavari shavad
############################################
####jalase 16#######
setwd("C:/Users/AS/Desktop/mohasebat97")
read.csv("data3.csv",header=T)
getwd()
##################################

