screechOwl
screechOwl

Reputation: 28159

R: Change levels inside a function

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(df1)
  id fact1
1  1     a
2  2     b
3  3     c
4  4     d
5  5     e
> levels(df1$fact1)[which(levels(df1$fact1) == 'a')] <- 'missing'
> df1
  id   fact1
1  1 missing
2  2       b
3  3       c
4  4       d
5  5       e

But if I try to do this inside a function it turns everything to the new value:

changeLevel1 <- function(x){
levels(x)[which(levels(x) == 'a')] <- 'missing'
}

df1$fact1 <- changeLevel1(df1$fact1)

> df1
  id   fact1
1  1 missing
2  2 missing
3  3 missing
4  4 missing
5  5 missing

What's the correct way to do this?

Upvotes: 2

Views: 108

Answers (1)

Justin
Justin

Reputation: 43255

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

Upvotes: 3

Related Questions