Its two one-liners.
Use cut
to create a factor:
ages <- round(runif(10, 0, 99))
ageF=cut(ages,c(-Inf,30,60,Inf),labels=c("young","mid","old"))
> ageF
[1] young mid young young old mid old young old old
Levels: young mid old
Usually you'd leave that as a factor and work with it, if you are using R's modelling functions they'll work out the matrix for you. But if you are doing it yourself:
Use model.matrix
to create the matrix, with a -1 to remove the intercept and create columns for each level:
> m = model.matrix(~ageF-1)
> m
ageFyoung ageFmid ageFold
1 1 0 0
2 0 1 0
3 1 0 0
4 1 0 0
5 0 0 1
6 0 1 0
7 0 0 1
8 1 0 0
9 0 0 1
10 0 0 1
attr(,"assign")
[1] 1 1 1
attr(,"contrasts")
attr(,"contrasts")$ageF
[1] "contr.treatment"
You can ignore all the contrasty stuff at the end, its just a matrix with some extra attributes for modelling.