Search code examples
rstringreplacefactorsgrepl

using grepl to fill a value in a variable produces strange results in R


I have a data.frame with a factor variable of 3 levels in R

'data.frame':   23848 obs. of  14 variables:
 $ Factor_var        : Factor w/ 3 levels "AAA","BBB",..: 1 1 3 3 3 3 2 2 2 2 ...

I want to overwrite one of the values with a different string using grepl function, but only if it is one of the values - otherwise it should remain the same

DF$Factor_var <- ifelse(grepl("AAA", DF$Factor_var), "ZZZ", DF$Factor_var)

After having run this transformation I get back chr variable with only string values that I just inpute, and values referring to the level value of the old strings

'data.frame':   23848 obs. of  14 variables:
  $ Factor_var       : chr  "ZZZ" "ZZZ" "3" "3" ...

whereas I am still expecting a factor variable with levels "ZZZ", "BBB" ... etc

Why is that? I just can't get around this problem!

THX


Solution

  • Use replace function for the same

    xy <-levels(df$Factor_var)
    
    xy <- replace(xy,xy%in%"AAA","ZZZ")
    
    levels(df$Factor_var) <- xy