-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPRESS.R
57 lines (45 loc) · 1.83 KB
/
PRESS.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
#====================================================================#
# Author: Damian Gwozdz (DG)
# Function: PRESS
# Creation date: 28JAN2018
# Last modified: -
# Description: Function to compute the PRESS stat
# required to calculate predicted R-squared
#
# Sources: 1) "Predictive R-squared according to Tom Hopper",
# https://rpubs.com/RatherBit/102428
# (access: 28JAN2018)
#
#====================================================================#
PRESS <- function(dset, target, vars, intercept = TRUE){
#====================================================================
# PARAMETERS:
#
# 1) dset - input data set
# 2) target - target variable declared as a string
# 3) vars - independent variables declared as a string
# with blanks as separators
# 4) intercept - a boolean value indicating whether the built model
# should have an intercept
#====================================================================
n <- nrow(dset)
ones <- rep(1, nrow(dset)-1)
specpr<-numeric(n)
vars.split <- unlist(strsplit(vars, " "))
if(intercept){
for(i in 1:nrow(dset)){
# If intercept, the column of size n x 1 (n is the number of
# observations in the dset): `ones` must be added
model<-fastLmPure(as.matrix(cbind(ones, dset[-i, vars.split])),
dset[[target]][-i])
specpr[i]<-sum(model$coefficients*unlist(c(1, dset[i, vars.split])))
}
}else{
for(i in 1:nrow(dset)){
model<-fastLmPure(as.matrix(dset[-i, vars.split]),
dset[[target]][-i])
specpr[i]<-sum(model$coefficients*unlist(dset[i, vars.split]))
}
}
return( sum((dset[[target]]-specpr)^2) )
}