Can someone explain what the foldid argument in glmnet does? I m trying to determine what alpha to use in my glmnet function, but the help file tells me:

Note that cv.glmnet does NOT search for values for alpha. A specific value should be supplied, else alpha=1 is assumed by default. If users would like to cross-validate alpha as well, they should call cv.glmnet with a pre-computed vector foldid, and then use this same fold vector in separate calls to cv.glmnet with different values of alpha. 

However, I do not understand:


*

*What the foldid vector / argument is.

*How to create the foldid vector 

*How to use foldid argument. 


Any assistance with this would be greatly appreciated!
 A: fold.id allows the user to pre-specify the cross validation folds for cv.glmnet.  For example, if I have some data
x    | y    | fold.id
-----+------+--------
0    | 1    | 1
1    | 1    | 1
0    | 0    | 2
1    | 2    | 2
.    | .    | .

Then passing in the indicated column as the fold.id argument to cv.glmnet will cause (for example) the first two observations to reside in the same fold, and the third and fourth observations to reside in the same (different) fold.
The authors are suggesting that if you would like to choose between some discrete collection of $\alpha$ based on a cross validation estimate of some error at an optimal $\lambda_{\alpha}$, then it is best practice to use the same fold structure in each of your cross validations when determining each $\lambda_{\alpha}$.
A: According to the Glmnet Vignette, one way to set-up the foldid for glmnet is by:
foldid<-sample(1:10,size=length(y),replace=TRUE)

And then apply to a series of alphas:
cv1=cv.glmnet(x,y,foldid=foldid,alpha=1)
cv.5=cv.glmnet(x,y,foldid=foldid,alpha=.5)
cv0=cv.glmnet(x,y,foldid=foldid,alpha=0)

The sample() function basically allows you to generate a vector of random numbers in the range you supply (= 1:nfolds) for the length of the response variable matrix y. In this way, you assign each of your input matrix rows to a random (but now set) fold.   
