One way is to use a vector with names to do the mapping: > mapVector <- c(A=8, B=11, C=3, D=2) > mapVector[as.character(d$fac)] B B D A C D C B B B 11 11 2 8 3 2 3 11 11 11 > # you may want to wrap this with unname() > d$mappedFac <- mapVector[as.character(d$fac)] > d x y fac mappedFac 1 1 1 B 11 2 1 2 B 11 3 1 3 D 2 4 1 4 A 8 5 1 5 C 3 6 1 6 D 2 7 1 7 C 3 8 1 8 B 11 9 1 9 B 11 10 1 10 B 11
Bill Dunlap TIBCO Software wdunlap tibco.com On Thu, Jul 17, 2014 at 8:00 AM, Gang Chen <gangch...@gmail.com> wrote: > Suppose I have the following dataframe: > > L4 <- LETTERS[1:4] > fac <- sample(L4, 10, replace = TRUE) > (d <- data.frame(x = 1, y = 1:10, fac = fac)) > > x y fac > 1 1 1 B > 2 1 2 B > 3 1 3 D > 4 1 4 A > 5 1 5 C > 6 1 6 D > 7 1 7 C > 8 1 8 B > 9 1 9 B > 10 1 10 B > > I'd like to add another column 'var' that is defined based on the > following mapping of column 'fac': > > A -> 8 > B -> 11 > C -> 3 > D -> 2 > > How can I achieve this in an elegant way (with a generic approach for > any length)? > > Thanks, > Gang > > ______________________________________________ > R-help@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. ______________________________________________ R-help@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.