-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstep_forward_ranking.r
More file actions
52 lines (48 loc) · 1.44 KB
/
step_forward_ranking.r
File metadata and controls
52 lines (48 loc) · 1.44 KB
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
# R code for ranking explanation variables according to AIC via forward stepwise.
#Yan Chen
### This is for testing purposes. ######################################
# data <- d
# initialf <- "y ~ "
# selected <- c()
# unselected <- snpname
# type <- "c"
# o <- stepforward(data, initialf, selected, unselected, type)
#########################################################################
stepforwardr <- function(data,initialf,selected,unselected, type){
n <- length(unselected)
times <- 0
minaic <- 0
lastaic <- 1
while(times < n){
aic <- c()
for(i in 1:length(unselected)){
fo <- formula(ifelse(length(selected)==0, paste0(initialf, unselected[i]),paste0(initialf,paste(selected,collapse="+"),"+", unselected[i])))
if(type=="c"){
fit <- lm(fo, data=data)
}else{
fit <- glm(fo, family=binomial(),data=data)
}
aic <- c(aic,AIC(fit))
}
#lastaic
if(length(selected) == 0){
lastaic <- Inf
}else{
lastfo <- formula(paste0(initialf, paste(selected,collapse="+")))
ifelse(type=="c", lastfit <- lm(lastfo,data=data), lastfit <- glm(lastfo, family=binomial(), data=data))
lastaic <- AIC(lastfit)
}
#minaic
minaic <- min(aic)
#judging
if(minaic < lastaic){
min.pos <- which.min(aic)
selected <- c(selected, unselected[min.pos])
unselected <- unselected[-min.pos]
times=times+1
}else{
break
}
}
return(list(times,selected))
}