简体   繁体   中英

Changing observation names in r

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?

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"

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM