[R] Creating a factor from a combination of vectors
Yves Brostaux
brostaux.y at fsagx.ac.be
Wed Dec 1 09:11:57 CET 2004
Thank you Richard, but I dismissed the 'ifelse' solution because it
needs explicit manual definition of the factor levels and corresponding
vectors' combinations and does not define it automaticaly from the
'cas' data-frame (from which values, number of levels and rownames can
vary).
Eric Lecoutre's code does exactly what I want, many thanks to both of you.
Richard A. O'Keefe a Ã©crit :
>Yves Brostaux <brostaux.y at fsagx.ac.be> wrote:
> I want to produce a factor from a subset of the combination of two
> vectors. I have the vectors a et b in a data-frame :
>
> > df <- expand.grid(a=c(0, 5, 10, 25, 50), b=c(0, 25, 50, 100, 200))
> ...
> and want to create a factor which levels correspond to particular
> combinations of a and b (let's say Low for a=0 & b=0, Medium for a=10 &
> b=50, High for a=50 & b=200, others levels set to NA), reading them from
> a data-frame which describes the desired subset and corresponding levels.
>
> Here's my own solution (inputs are data-frames df and cas, output is the
>
>Why not do it the obvious way?
>
> ifelse(a == 0 & b == 0, "Low",
> ifelse(a == 10 & b == 50, "Medium",
> ifelse(a == 50 & b == 200, "High",
> "Other")))
>
>gives you the mapping from vectors a and b to strings you want.
>To get at the vectors locally, you need
>
> with(df, ...)
>
>To convert the vector of strings you get to an ordered factor,
>with "Other" mapped to NA, just do
>
> ordered(..., levels = c("Low","Medium","High"))
>
>because any string not listed in levels= will be mapped to NA.
>Put these pieces together, and you get
>
> output <- ordered(with(df,
> ifelse(a == 0 & b == 0, "Low",
> ifelse(a == 10 & b == 50, "Medium",
> ifelse(a == 50 & b == 200, "High",
> "Other")))),
> levels = c("Low","Medium","High"))
>
>
>
>
>
--
Ir. Yves BROSTAUX
UnitÃ© de Statistique et Informatique
FacultÃ© universitaire des Sciences agronomiques de Gembloux (FUSAGx)
8, avenue de la FacultÃ©
B-5030 Gembloux
Belgique
TÃ©l: +32 81 62 24 69
Email: brostaux.y at fsagx.ac.be
More information about the R-help
mailing list