-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmodule_two_core.R
70 lines (51 loc) · 1.67 KB
/
module_two_core.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# ================ CORE FUNCTIONS FOR MODULE TWO =================
## =========================== Correlation ======================================
my_cor<-function(x,y) {
# x and y must be multile data with same length
# In built
# x<-c(8,9,7,6,13,7,11,12)
# y<-c(35,49,27,33,60,21,45,51)
# cor(x,y)
if(length(x)==length(y)){
n<-length(x)
r<-( n * sum(x**2) - (sum(x)**2) ) * ( n * sum(y**2) - (sum(y)**2) )
r<-sqrt(r)
r<-1/r
r<-( n * sum(x*y) - sum(x) *sum(y) ) * r
# 6 digit precision
result <- as.numeric(formatC(r,digits = 6,format = "f"))
return(result)
}
else{
return("Error : X and Y must be of same length.")
}
}
#null hypothesis r=0
#alternative hypothesis r!=0
my_cor_significance_test<-function(r,n,alpha){
# r is correlation
# lenght of dataset
# alpha : level of significance
t<-r/sqrt((1-r**2)/(n-2))
if(t<0) {
t<-abs(t)
}
critical_value<-qt(1-alpha/2,n-2)
return(c(critical_value,t))
}
## ========================== Multi Linear Regression ======================================
my_multi_linear_regression<-function(x1 , x2 , y ) {
if(length(x1)==length(x2)){
xMatrix<-cbind(c(length(x1),sum(x1),sum(x2)) ,
c(sum(x1),sum(x1**2),sum(x1*x2)) ,
c(sum(x2),sum(x1*x2),sum(x2**2)))
xyMatrix<-cbind(c(sum(y),
sum(x1*y),
sum(x2*y)))
result<-solve(xMatrix,xyMatrix) #matrix inverse , then multiply with inverse and save final result in result
return(c(result[1][1] ,result[2][1], result[3][1]))
}
else{
return("Error : X1 and X2 must be of same length.")
}
}