R: Change levels inside a function

后端 未结 1 1344
臣服心动
臣服心动 2021-01-21 20:50

I have a data.frame and I want to change levels of a factor variable so I do this:

> df1 <- data.frame(id = 1:5, fact1 = factor(letters[1:5]))
> head(df         


        
相关标签:
1条回答
  • 2021-01-21 21:16

    you need to return the full object x rather than just the result of your assignment (which is the string missing).

    changeLevel1 <- function(x){
       levels(x)[which(levels(x) == 'a')] <- 'missing'
       return (x)
    }
    
    0 讨论(0)
提交回复
热议问题