[R] Mapping from one vector to another

Gang Chen gangchen6 at gmail.com
Thu Jul 17 17:00:21 CEST 2014


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



More information about the R-help mailing list