Re: [R] Recoding

From: Marc Schwartz <marc_schwartz_at_comcast.net>
Date: Fri, 27 Jun 2008 14:33:36 -0500

on 06/27/2008 01:41 PM Agustin Lobo wrote:
> Hi!
>
> Given a vector (or a factor within a df),i.e. v1 <- c(1,1,1,2,3,4,1,10,3)
> and a dictionary
> cbind(c(1,2,3),c(1001,1002,1003))
>
> is there a function (on the same line than recode() in car)
> to get v2 as c(1001,1001,1001,1002,1003,4,1001,10,1003) ?
>
> I'm using myself a function based on match() since
> long ago (I think that thanks to advice by Prof. B. Ripley),
> but would like to know if there is an standard function (i.e., like
> recode()). What I'm using is:
>
> "reclas" <- function(v, origen, imagen, directo = T, resto=1)
> {
> if(directo == F) {
> aux <- origen
> origen <- imagen
> imagen <- aux
> }
> m <- match(v, origen, 0)
> #print("match finished")
> if(resto==0) v <- v*0
> v[m > 0] <- imagen[m]
> v
> }
>
> Agus
>

v1 <- c(1,1,1,2,3,4,1,10,3)
dic <- cbind(c(1,2,3),c(1001,1002,1003))

Ind <- match(v1, dic[, 1])

 > Ind
[1] 1 1 1 2 3 NA 1 NA 3

 > sapply(seq(along = Ind),

          function(x) if (is.na(Ind[x])) v1[x] else dic[Ind[x], 2]) [1] 1001 1001 1001 1002 1003 4 1001 10 1003

I would certainly test that a bit more to be sure it works on other data.

HTH, Marc Schwartz



R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Fri 27 Jun 2008 - 19:35:57 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 27 Jun 2008 - 20:33:01 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive