Search code examples
rrecode

How to recode multiple-conditionals to -1/0/+1?


I have my data like:

Name A B C
apple 1 -1 0
banana 2 -2 1
pear -3 0 1

I want to replace all positive value to -1, all negative values to +1, but remain the 0 to be 0, how do I achieve that?


Solution

  • We could use sign to get the sign of all the elements of the dataframe and then reverse it by multiplying it to -1.

    df[-1] <- sign(df[-1]) * -1
    
    df
    #    Name  A B  C
    #1  apple -1 1  0
    #2 banana -1 1 -1
    #3   pear  1 0 -1
    

    From ?sign

    sign returns a vector with the signs of the corresponding elements of x (the sign of a real number is 1, 0, or -1 if the number is positive, zero, or negative, respectively).

    data

    df <- structure(list(Name = structure(1:3, .Label = c("apple", "banana", 
    "pear"), class = "factor"), A = c(-1, -1, 1), B = c(1, 1, 0), 
    C = c(0, -1, -1)), .Names = c("Name", "A", "B", "C"), row.names = c(NA, 
    -3L), class = "data.frame")