[R] Mapping from one vector to another

Gang Chen gangchen6 at gmail.com
Thu Jul 17 17:39:56 CEST 2014


Thanks a lot for the quick and elegant solutions, Sarah, Bill and
Petr! I really appreciate it, including the suggestion of setting a
random seed. Have a nice day!

Gang

On Thu, Jul 17, 2014 at 11:15 AM, Sarah Goslee <sarah.goslee at gmail.com> wrote:
> What about:
>
> d$var <- c(8, 11, 3, 2)[d$fac]
>
> Side note: it's much appreciated that you included data and a clear
> problem statement. If you use
> set.seed(123)
> before your call to sample(), everyone who tries it will get the same
> fac that you do. Otherwise we all get something different. Or just
> generate your own example data and use dput() to include it in your
> email.
>
> Sarah
>
> On Thu, Jul 17, 2014 at 11:00 AM, Gang Chen <gangchen6 at 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
>>
> --
> Sarah Goslee
> http://www.functionaldiversity.org



More information about the R-help mailing list