Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close


Excellent! What if you would like to add a new level to an existing factor variable? We've already seen that you'll get a warning if you attempt to add an uncategorized value to a factor, and R will replace it with NA. Let's take a quick look at an example. In the houses$district column, we've stored the districts in which properties are open for sale. Suppose our real estate agency has decided to sell homes in the "Manty Avenue" district, and we want to add that new category to our houses$district column. What do we do in that case?

We can use the factor() function once again to add new levels. First, a refresher: recall that the c() function does not have to take just raw values—it can also accept vector arguments. So, to make our lives easier, we can add the new factor level "Manty Avenue" like so, without retyping all the other levels:

houses$district<- factor(houses$district, levels=c(levels(houses$district), "Manty Avenue") )

Now, when you run

houses[1, "district"] <- "Manty Avenue"
R will not give you any warnings because "Manty Avenue" was successfully added as a level.


Add a new category named "U" to the existing factor variable called air_conditioner (in the houses data frame). We'll use "U" for unknown/missing values.