Replace contents of factor column in R dataframe

后端 未结 8 1662
我在风中等你
我在风中等你 2020-11-28 20:59

I need to replace the levels of a factor column in a dataframe. Using the iris dataset as an example, how would I replace any cells which contain virginic

8条回答
  •  眼角桃花
    2020-11-28 21:28

    In case you have to replace multiple values and if you don't mind "refactoring" your variable with as.factor(as.character(...)) you could try the following:

    replace.values <- function(search, replace, x){
      stopifnot(length(search) == length(replace))
      xnew <- replace[ match(x, search) ]
      takeOld <- is.na(xnew) & !is.na(x)
      xnew[takeOld] <- x[takeOld]
      return(xnew)
    }
    
    iris$Species <- as.factor(search=c("oldValue1","oldValue2"),
                              replace=c("newValue1","newValue2"),
                              x=as.character(iris$Species))
    

提交回复
热议问题