# [R] Creating a factor from a combination of vectors

Richard A. O'Keefe ok at cs.otago.ac.nz
Wed Dec 1 02:37:27 CET 2004

```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"))

```