[R] Vector Assignments

Gabor Grothendieck ggrothendieck at myway.com
Tue Dec 2 06:32:30 CET 2003



And one other thing.  Are you sure you want character variables
as the result of all this?  A column whose entries are each one
of four colors seems like a good job for a factor:

colours <- c("red", "blue", "green","black")
cut(x, c(-Inf,250,500,700,Inf),right=F,lab=colours)



---
Date: Mon, 1 Dec 2003 23:47:39 -0500 (EST) 
From: Gabor Grothendieck <ggrothendieck at myway.com>
To: <h.wickham at auckland.ac.nz>, <apv at capital.net> 
Cc: <r-help at stat.math.ethz.ch> 
Subject: Re: [R] Vector Assignments 

 
 


Just some small refinements/corrections:

colours <- c("red", "blue", "green","back")
colours[cut(x, c(-Inf,250,500,700,Inf),right=F,lab=F)]

---
Date: Tue, 02 Dec 2003 14:38:55 +1300 
From: Hadley Wickham <h.wickham at auckland.ac.nz>
To: Arend P. van der Veen <apv at capital.net> 
Cc: R HELP <r-help at stat.math.ethz.ch> 
Subject: Re: [R] Vector Assignments 



One way would be to create a vector of colours and then cut() to index 
the vector:

colours <- c("red", "blue", "green","back")
colours[cut(x, c(min(x),250,500,700,max(x)),lab=F)]

Hadley


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
>




More information about the R-help mailing list