简体   繁体   中英

In R: replacing specific factor in a dataframe with another existing factor

I have a large data frame with a variable 'home_ownership' which can take the factors : 'own', 'mortgage', 'none', 'other'

I want to replace the values which are 'none' to 'other' .

I tried

df$home_ownership[df$home_owneship == "none"] <- "other"

which runs without an error.

But then when I do table(df$home_ownership) I still get a count of 46 for "none" Whilst I was expecting it (and wanting) it to have a count of 0.

there's a typo in

df$home_ownership[df$home_owneship == "none"] <- "other"

with the missing r it should do what you want ;)

--

But if you're really talking about the levels of a factor this should help:

levels(df$home_ownership)[levels(df$home_ownership)=="none"] <- "other"

or use factor() again after replacing the value. For renaming levels look here .

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