Search code examples
rfor-loopif-statementabsolute-value

Chnging the value of columns from postive to negative


ID   Y     Z     W
1    aa   AA    -6.8
2    bb    FF      5.8
3     cc    DD     -9.25
.      .     .      .
.       .    .       .
.        .    .       .

i want to changes the above data frame replacing the negative value by postive values in such case the value of column Y and Z are also changed. The new data frame looks like

ID   Y     Z     W
1    aa   aa    6.8
2    bb    FF      5.8
3     cc    cc    9.25
.      .     .      .
.       .    .       .
.        .    .       .

Any one can help me with the r code ? thanks


Solution

  • Something like this should get the job done.

    library("dplyr")
    
    Y <- c("aa","bb","cc")
    Z <- c("aa", "FF", "cc")
    W <- c(-6.8,5.8,-9.25)
    
    Test_Data <- data.frame(Y,Z,W) 
    
    New_Data <- Test_Data %>%
      mutate(
        Z = if_else(W<0,Y,Z),
        W = abs(W)
        )