How to convert only SOME positive numbers to negative numbers (conditional recoding)?

TiF picture TiF · Aug 17, 2012 · Viewed 9.6k times · Source

I am looking for a convenient way to convert positive values (proportions) into negative values of the same variable, depending on the value of another variable.

This is how the data structure looks like:

id Item Var1  Freq 
1  P1   0    0.043
2  P2   1    0.078
3  P3   2    0.454
4  P4   3    0.543
5  T1   0    0.001
6  T2   1    0
7  T3   2    0.045
8  T4   3    0.321
9  A1   0    0.671
...

More precisely, I would like to put the numbers for Freq into the negative if Var1 <= 1 (e.g. -0.043).

This is what I tried:

for(i in 1: 180) {
if (mydata$Var1 <= "1") (mydata$Freq*(-1))}

OR

mydata$Freq[mydata$Var1 <= "1"] = -abs(mydata$Freq)}

In both cases, the negative sign is rightly set but the numbers are altered as well.

Any help is highly appreciated. THANKS!

Answer

Backlin picture Backlin · Aug 17, 2012
new.Freq <- with(mydata, ifelse(Var1 <= 1, -Freq, Freq))