Add extra level to factors in dataframe

后端 未结 5 1261
时光取名叫无心
时光取名叫无心 2020-11-30 04:09

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

5条回答
  •  伪装坚强ぢ
    2020-11-30 04:41

    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")
    

提交回复
热议问题