Home > database >  Reverse negatives for numeric values according to category in R
Reverse negatives for numeric values according to category in R

Time:08-02

I have a data frame that looks like so:

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

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

Does anyone know a method for doing so?

CodePudding user response:

Try this using ifelse function

df$evaluation <-  ifelse(df$colour == "black" & grepl("\\ " , df$evaluation),
sub("\\ " , "-" , df$evaluation) ,
ifelse(df$colour == "black" & grepl("\\-" , df$evaluation) ,
sub("\\-" , " " , df$evaluation) , df$evaluation))
  • output
  colour evaluation
1  white       1.00
2  black       0.50
3  white     - 0.60
4  black     - 1.50
  • data
df <- structure(list(colour = c("white", "black", "white", "black"), 
    evaluation = c("  1.00", "  0.50", "- 0.60", "- 1.50")), row.names = c(NA, 
-4L), class = "data.frame")

CodePudding user response:

Use the swap function from the textclean package

df <- data.frame(colour = c("white", "black", "white", "black"), evaluation = c("  1.00", "- 0.50", "- 0.60", "  1.50"))

library(dplyr); library(textclean)
df %>% 
  mutate(evaluation = ifelse(colour == 'black', swap(evaluation,' ', '-'), evaluation))

  colour evaluation
1  white       1.00
2  black       0.50
3  white     - 0.60
4  black     - 1.50
  • Related