Search code examples
rwarningsdata-cleaning

Renaming variable names in R.


I want to replace "LF" with "Low Fat" and this is the code i used:

train$Item_Fat_Content[train$Item_Fat_Content =="LF"]= "Low FAt"

When I executed the code I got the warning message stating:

In `[<-.factor`(`*tmp*`, train$Item_Fat_Content == "LF", value = c(3L,  :
  invalid factor level, NA generated

Solution

  • We can convert it to character class and then do the assignment

    train$Item_Fat_Content <- as.character( train$Item_Fat_Content)
    train$Item_Fat_Content[train$Item_Fat_Content =="LF"]= "Low FAt"
    

    Or if we want to preserve the class as factor, before doing the assignment, create a level as "Low FAt" and then do the assignment

    levels(train$Item_Fat_Content) <- c(levels(train$Item_Fat_Content), "Low FAt")
    

    NOTE: As @doviod mentioned in the comments, while reading the data with read.table/read.csv, use the stringsAsFactors = FALSE if we want to have non-numeric columns as character class (unless there is a specific reason to have factor columns)