TiF
TiF

Reputation: 625

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

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!

Upvotes: 2

Views: 11320

Answers (3)

Irfan
Irfan

Reputation: 1

It can also be used to deal with two variables when one has negative values and want to combine that by retaining negative values, similarly can use it to convert to negative value by put - at start of variable (as mentioned above) e.g. -Freq.

mydata$new_Freq <- with(mydata, ifelse(Var1 < 0, Low_Freq, Freq))


id Item Var1  Freq  Low_Freq
1  P1   0    1.043  -0.063
2  P2   1    1.078  -0.077 
3  P3   2    2.401  -0.068  
4  P4   3    3.543  -0.323
5  T1   0    1.001   1.333
6  T2   1    1.778   1.887 
7  T3   2    2.045   1.011
8  T4   3    3.321   1.000
9  A1   0    4.671   2.303



# Output would be:

id Item Var1  Freq  Low_Freq   new_Freq
1  P1   0    1.043  -0.063     -0.063
2  P2   1    1.078  -0.077     -0.077
3  P3   2    2.401  -0.068     -0.068
4  P4   3    3.543  -0.323     -0.323
5  T1   0    1.001   0.999      1.001
6  T2   1    1.778   0.887      1.778
7  T3   2    2.045   1.011      2.045
8  T4   3    3.321   1.000      3.321
9  A1   0    4.671   2.303      4.671

Upvotes: 0

Andrie
Andrie

Reputation: 179578

Try:

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

There are two errors in your attempted code:

  • You did a character comparison by writing x <= "1" - this should be a numeric comparison, i.e. x <= 1
  • Although you are replacing a subset of your vector, you don't refer to the same subset as the replacement

Upvotes: 3

Backlin
Backlin

Reputation: 14872

new.Freq <- with(mydata, ifelse(Var1 <= 1, -Freq, Freq))

Upvotes: 4

Related Questions