[R] Vector Assignments

Thomas W Blackwell tblackw at umich.edu
Tue Dec 2 02:40:08 CET 2003


Arend  -

Here is a sequence of commands which will do it.
These first build a vector of (4+1) cutpoints,
then  cut()  returns a factor whose labels are
the colors and codes are determined by x.  Last,
as.character()  turns the factor into the character
vector which you ask for.  Or, perhaps the factor
data structure is more useful directly.  (Factors
are sort of an acquired taste.)

Note that in the call to cut, I am passing many
arguments into the function by their position in
the call.  You will need to look at  help("cut")
to figure out which argument is which.  Note also
that by monkeying with the two logical arguments,
("include.lowest" and "right"), I didn't need to
fudge any of the cutpoints.

tmp <- range(x)
tmp <- c(tmp[1], 250, 500, 750, tmp[2])
fac <- cut(x, tmp, c("red","blue","green","black"), TRUE, FALSE)
col <- as.character(fac)

HTH  -  tom blackwell  -  u michigan medical school  -  ann arbor  -

On Mon, 1 Dec 2003, Arend P. van der Veen wrote:

> Hi,
>
> I have simple R question.
>
> I have a vector x that contains real numbers.  I would like to create
> another vector col that is the same length of x such that:
>
> if x[i] < 250 then col[i] = "red"
> else if x[i] < 500 then col[i] = "blue"
> else if x[i] < 750 then col[i] = "green"
> else col[i] = "black" for all i
>
> I am convinced that there is probably a very efficient way to do this in
> R but I am not able to figure it out.  Any help would be greatly
> appreciated.
>
> Thanks in advance,
> Arend van der Veen
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
>




More information about the R-help mailing list