[R] Recode of text variables

Rolf Turner r.turner at auckland.ac.nz
Thu Apr 2 01:40:27 CEST 2009


On 2/04/2009, at 12:22 PM, Andrew McFadden wrote:

> Hi all
>
> I am trying to do a simple recode which I am stumbling on. I figure
> there must be any easy way but haven't come across it.
>
> Given data of A","B","C","D","E","A" it would be nice to recode this
> into say three categories ie A and B becomes "Treat1", C becomes  
> "Treat
> 2" and E becomes "Treat 3".
>
> I tried the car library but it didn't seem to like text. Also it seems
> you can only recode into two categories.
>
>
> library(car)
>
> x<-c("A","B","C","D","E","A")
> x
> recode(x, "c(A,B)='Treat 1'; else='Treat 2'")
> recode(x, "1:2='A'; 3='B'")
>
> In Microsoft access a simple way of recoding is to join two tables  
> in a
> query any simple way of doing the same in R?

y <- c("Treat 1","Treat 1","Treat 2","Blechh!","Treat 3")[match 
(x,LETTERS[1:5])]

is one way of doing it.  There are a brazillion others (using  
factors, levels,
and labels for instance).  Some of them may be sexier than my  
suggestion above.

Note that D gets recoded as ``Blechh!'' in the my suggestion, since  
you didn't
specify what you wanted to happen to D.  If you want D to stay as D,  
replace
"Blechh!" by "D"; or if you want it to becoming ``missing'' replace  
"Blechh!"
by NA.

	cheers,

		Rolf Turner

######################################################################
Attention:\ This e-mail message is privileged and confid...{{dropped:9}}




More information about the R-help mailing list