luciano luciano -4 years ago 115
R Question

Replace contents of factor column in R dataframe

I need to replace the levels of a factor column in a dataframe. Using the

dataset as an example, how would I replace any cells which contain
in the Species column?

I expected the following to work, but it generates a warning message and simply inserts NAs:

iris$Species[iris$Species == 'virginica'] <- 'setosa'

Answer Source

I bet the problem is when you are trying to replace values with a new one, one that is not currently part of the existing factor's levels:

# [1] "setosa"     "versicolor" "virginica" 

Your example was bad, this works:

iris$Species[iris$Species == 'virginica'] <- 'setosa'

This is what more likely creates the problem you were seeing with your own data:

iris$Species[iris$Species == 'virginica'] <- 'new.species'
# Warning message:
# In `[<-.factor`(`*tmp*`, iris$Species == "virginica", value = c(1L,  :
#   invalid factor level, NAs generated

It will work if you first increase your factor levels:

levels(iris$Species) <- c(levels(iris$Species), "new.species")
iris$Species[iris$Species == 'virginica'] <- 'new.species'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download