Search code examples
rreplacemax

Converting Highest value of rows to 1 and rest to 0


I wasn't sure if creating an if statement would be the best way, but I need code to identify the column with the highest rowmax and replace it with a 1 and the other columns of that specific row get replaced with a 0. I have about 5,000 lines of code.

I am trying to find the row with the highest max value (dataframe) and need to replace the highest row max value with a 1 and the other values with a 0 ( 6 variables/columns with 5,000 rows/obs.)

Thank you!


Solution

  • One approach in base R (similar to what Gregor Thomas already posted):

    Generate example data:

    df <- data.frame("row1" = c(1,2,3),
               "row2" = c(1,2,3),
               "row3" = c(1,99,3))
    
      row1 row2 row3
    1    1    1    1
    2    2    2   99
    3    3    3    3
    

    Proposed solution:

    result <- t(apply(df, 1, function(x) ifelse(x == max(x), 1, 0)))
    
         row1 row2 row3
    [1,]    1    1    1
    [2,]    0    0    1
    [3,]    1    1    1
    

    Conversion back to your exact input data format:

    as.data.frame(result, row.names = rownames(df), colnames = names(df))
    
      row1 row2 row3
    1    1    1    1
    2    0    0    1
    3    1    1    1