[R] Multiply variable by condition

David Winsemius dwinsemius at comcast.net
Fri Jun 1 23:23:19 CEST 2012


On Jun 1, 2012, at 2:37 PM, Sarah Goslee wrote:

> There are several ways. The easiest to understand is probably using
> if() statements: see ?if for help and examples.
>
> Sarah
>
I would have thought ifelse() to be the necessary function, but for  
such simple cases I find boolean math to be clearer. (I understand  
indivdiual preferences vary in this area.)

 > dft <-data.frame(Y=1, M=sample(c(1,3,9),20,repl=TRUE))

 > dft$res <- with(dft, Y*( (M==1) *1 + (M==3)*2 +(M==9)*3.6678) )
 > dft
    Y M    res
1  1 1 1.0000
2  1 9 3.6678
3  1 3 2.0000
4  1 1 1.0000
5  1 1 1.0000
6  1 9 3.6678
7  1 9 3.6678
8  1 9 3.6678
9  1 3 2.0000
10 1 9 3.6678
11 1 9 3.6678
12 1 9 3.6678
13 1 1 1.0000
14 1 3 2.0000
15 1 3 2.0000
16 1 1 1.0000
17 1 1 1.0000
18 1 3 2.0000
19 1 9 3.6678
20 1 9 3.6678

-- 
David
> On Fri, Jun 1, 2012 at 11:34 AM, jfca283 <jfca283 at gmail.com> wrote:
>> Hi
>> I need to do something very simple. I have 2 variables, Y and M. I  
>> need to
>> multiply Y by 1 if M=1, by 2 if M=3 and by 3.6678 if M=9. How do i  
>> make it?
>> Thanks for your time and interest
>>
>
-- 

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list