OneSolitaryNoob
OneSolitaryNoob

Reputation: 5737

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?

Upvotes: 0

Views: 81

Answers (1)

HubertL
HubertL

Reputation: 19544

You can use factor instead of as.factor:

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

Upvotes: 2

Related Questions