Search code examples
rdata-cleaningdata-wrangling

Reverse negatives for numeric values according to category in R


I have a data frame that looks like so:

colour evaluation
white 1.00
black - 0.50
white - 0.60
black 1.50

Evaluations is a numeric data type.

I want to create code that flips all the symbols of all evaluations with the colour black, so + becomes - and - becomes +, to create a table like so:

colour evaluation
white 1.00
black 0.50
white - 0.60
black - 1.50

This is the dput() output of the first 20 rows of my data frame:

structure(list(nnue_diff = c(NA, 0.12, -0.05, 0.06, -0.03, 0.13, 
-0.05, 0.02, 0.13, -0.22, -0.08, 0.07, -0.2, 0.24, -0.16, 0.32, 
1.18, -1.23, -0.06, 0), colour = c("white", "black", "white", 
"black", "white", "black", "white", "black", "white", "black", 
"white", "black", "white", "black", "white", "black", "white", 
"black", "white", "black")), row.names = c(NA, -20L), class = c("tbl_df", 
"tbl", "data.frame"))

Does anyone know a method for doing so?


Solution

  • Based on updated data

    library(dplyr)
    
    df |> mutate(nnue_diff = case_when(colour == "black" ~ nnue_diff * -1 , TRUE ~ nnue_diff))
    
    • output
    # A tibble: 20 × 2
       nnue_diff colour
           <dbl> <chr> 
     1     NA    white 
     2     -0.12 black 
     3     -0.05 white 
     4     -0.06 black 
     5     -0.03 white 
     6     -0.13 black 
     7     -0.05 white 
     8     -0.02 black 
     9      0.13 white 
    10      0.22 black 
    11     -0.08 white 
    12     -0.07 black 
    13     -0.2  white 
    14     -0.24 black 
    15     -0.16 white 
    16     -0.32 black 
    17      1.18 white 
    18      1.23 black 
    19     -0.06 white 
    20      0    black