While loop

#1
Hello folks,
first of all sorry if my english isn’t perfect.

I working on last chapter of my graduation thesis and I have a big problem. I using the package Lasso2 in R and I need to estimate the parameter t with a generalized cross validation. For do that, in the package, there is the gcv function. So I wrote a while loop in R but it don’t working. So I need help.

Code:
i=1
tmax=1
t=0
tinc=0.1

while (t<tmax)
model=l1ce(y_m ~ x_m_1+x_l_1+x_r_1+x_m_2+x_l_2+x_r_2+x_m_3+x_l_3+x_r_3+x_4,bound = t, absolute.t=FALSE)
cv=gcv.l1ce(model, type=c("Tibshirani"))
t=t+tinc
i=i+1
I really need some help plz.
 

Mike White

TS Contributor
#2
I think that you just need to enclose the code after the while condition in curly brackets as below. However, t and tinc are not being evaluated within the while statement so you could just as easily use a for loop.
Code:
while (t<tmax) {
model=l1ce(y_m ~ x_m_1+x_l_1+x_r_1+x_m_2+x_l_2+x_r_2+x_m_3+x_l_3+x_r_3+x_4,bound = t, absolute.t=FALSE)
cv=gcv.l1ce(model, type=c("Tibshirani"))
t=t+tinc
i=i+1
}
 
#3
Ok tnx very much, the problem now is that. I have only the last cv estimate but i need all cvs, for all iteration of the loop. It's possible?
 

Dason

Ambassador to the humans
#4
Of course it's possible. Just initialize an empty vector before the loop and add the item to the correct place during the loop.

Edit: I didn't look too much into it but if what you have isn't a base data type you might need to use a list instead of a vector.
 
#5
Of course it's possible. Just initialize an empty vector before the loop and add the item to the correct place during the loop.
Yes i trying for that, i already created an empty vector before the loop with

vet=vector(mode="numeric",length=i)
but now i dont know how add item on it during the loop :D


ps:Yes i worknig on a base data.
 

Dason

Ambassador to the humans
#6
Here's a simple example that you should be able to adapt to your needs.

Code:
vet <- 0
for(i in 1:10){
   vet[i] <- 2*i
}
vet
Looking at your code there is no reason to use a while loop. Also why are you using an increment of .1? Why are you keeping track of i? You don't seem to use i for anything. You clearly know how many times you want this to run so using a for loop would probably be the better option.

Note: The code I wrote is one of the worst ways to multiply all of the elements in a vector by 2 but it serves its purpose as an example.