Affect a value without replacing if the value is not empty

Hi! I have a column to class my data in different categories like 'AB', 'KD', 'other'.
But in my column "Class", some rows were already classified before as 'classb' for example and I don't want the values to be replaced. I don't know how to do. I do my classification with

mutate(class = case_when(cond1 ~ "AB",...))

To illustrate I have this :
Id / result / difftime / class
12 / 2 / 12 /
45 / 1 / 24 / classb
33 / 1 / 12 /

and I want this :
Id / result / difftime / class
12 / 2 / 12 / KD
45 / 1 / 24 / classb
33 / 1 / 12 / AB

instead of this :
Id / result / difftime / class
12 / 2 / 12 / KD
45 / 1 / 24 / AB
33 / 1 / 12 / AB

I would like to specify that I try to add as a condition class == 'class2' ~ 'class2' to keep the same value but it doesn't worked.
I hope I was clear. Thank you for your time.

Hello,

Here is a way of doing this

library(dplyr)

df = data.frame(
  id = 1:5,
  class = NA
)

df$class[3] = "classb"
df
#>   id  class
#> 1  1   <NA>
#> 2  2   <NA>
#> 3  3 classb
#> 4  4   <NA>
#> 5  5   <NA>

df %>% mutate(class = case_when(
  class == "classb" ~ class,
  id > 4 ~ "X",
  TRUE ~ 'Y'
))
#>   id  class
#> 1  1      Y
#> 2  2      Y
#> 3  3 classb
#> 4  4      Y
#> 5  5      X

Created on 2022-03-31 by the reprex package (v2.0.1)

Basically, when you don't want the result to change, you put the same variable as output

Hope this helps,
PJ

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.