Home > OS >  Changing observation names in r
Changing observation names in r

Time:08-09

I have a dataset of 'Customers' and one of the variables is 'type' which consists of 4 observations - CAR INSURANCE, car insurance, life insurance and home content/building insurance. I want to change 'CAR INSURANCE' to 'car insurance' to have 3 observations. I have tried the following but none of which seem to work:

mutate(Type = ifelse(Type == "CAR INSURANCE", "car insurance", Type))
rename(Type, "CAR INSURANCE" == "car insurance")
Insurance_df = data.frame("Type" = c("CAR INSURANCE", "car insurance","life insurance",
                                     "home content/building insurance"))
Insurance_df = rename(Insurance_df, "car insurance" = "CAR INSURANCE")

Can someone point me in the right direction?

CodePudding user response:

If its the exactly the same string you can try something like this, in order to get only lower case strings:

df <- data.frame("type" = c("CAR INSURANCE", "car insurance", "life insurance"))
df$type <- tolower(df$type)

Alternatively, to be more flexible:

df[df$type == "CAR INSURANCE", ] <- "car insurance"

CodePudding user response:

If the column df$type is a factor (this will be the default if you're using R < 4), then the following will be more efficient:

levels(df$type) <- tolower(levels(df$type))
  •  Tags:  
  • r
  • Related