[R] how to make automatically each level from data.frame to vector

Muhammad Subianto subianto at gmail.com
Sat Nov 12 21:37:27 CET 2005


Dear R-helpers,
Suppose I have dataset like this below:
data(HairEyeColor)
dfHEC <- as.data.frame(as.table(HairEyeColor))
my.dfHEC <- data.frame(Hair=rep(dfHEC$Hair,dfHEC$Freq),
                       Eye=rep(dfHEC$Eye,dfHEC$Freq),
                       Sex=rep(dfHEC$Sex,dfHEC$Freq))
my.dfHEC
my.dfHEC$Hair
my.dfHEC$Eye
my.dfHEC$Sex

and I know all levels for Hair, Eye and Sex.
In my case, I want to "expand.grid" all attributes but in Hair I only
include "Black" hair:

Hair.e <- c("Black")
Eye.e <- c("Brown","Blue","Hazel","Green")
Sex.e <- c("Male","Female")

#I can do like,
dfHEC.Black <- expand.grid(Hair.e,Eye.e,Sex.e)
dfHEC.Black

My question is how to make automatically each level from data.frame to vector.
I don't want to make definition for each level again (Hair.e, Eye.e, Sex.e).
In the others word, how can I make "expand.grid" (each level) from
data.frame automatically if Hair is only ("Black").
The result I need like,

   Var1  Var2   Var3
1 Black Brown   Male
2 Black  Blue   Male
3 Black Hazel   Male
4 Black Green   Male
5 Black Brown Female
6 Black  Blue Female
7 Black Hazel Female
8 Black Green Female

Thanks in advance.
Best, Muhammad Subianto




More information about the R-help mailing list