OneSolitaryNoob OneSolitaryNoob - 1 year ago 109
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:

Factor w/ 297 levels "san francisco","atlanta",..: 186


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

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

Answer Source

You can use factor instead of as.factor:

one_row_df$city <- factor("new york", levels=c(levels(one_row_df$city), "new york"))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download