我有一个 data.frame,我想更改因子变量的级别,所以我这样做:
> 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
但是,如果我尝试在函数中执行此操作,它会将所有内容都转换为新值:
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
这样做的正确方法是什么?