I have a data frame with numeric and ordered factor columns. I have lot of NA values, so no level is assigned to them. I changed NA to \"No Answer\", but levels of the facto
Expanding on ilir's answer and its comment, you can check if a column is a factor and that it does not already contain the new level, then add the level and thus make the function re-runable:
addLevel <- function(x, newlevel=NULL) {
if(is.factor(x)) {
if (is.na(match(newlevel, levels(x))))
return(factor(x, levels=c(levels(x), newlevel)))
}
return(x)
}
You can then apply it like so:
dataFrame$column <- addLevel(dataFrame$column, "newLevel")