OneSolitaryNoob OneSolitaryNoob - 7 days ago 6
R Question

R: change value in a dataframe without losing factor levels

I'm trying to set one value in a dataframe, without losing the levels. Just setting the value seems to reduce levels to 1. Initally:

str(one_row_df$city)
Factor w/ 297 levels "san francisco","atlanta",..: 186


Settings:

one_row_df$city <- as.factor("new york")
str(one_row_df$city)
Factor w/ 1 level "new york": 1


How do I set this field without losing all the factor levels?

Answer

You can use factor instead of as.factor:

one_row_df$city <- factor("new york", levels=c(levels(one_row_df$city), "new york"))
Comments