R:更改函数内的级别 [英] R: Change levels inside a function
本文介绍了R:更改函数内的级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
>我有一个data.frame,我想改变一个因子变量的级别,所以我这样做: df1< - data.frame(id = 1:5,fact1 = factor(字母[1:5]))
> head(df1)
id fact1
1 1 a
2 2 b
3 3 c
4 4 d
5 5 e
> gt ; (df1 $ fact1)[which(levels(df1 $ fact1)=='a')]] < - 'missing'
> df1
id fact1
1 1缺少
2 2 b
3 3 c
4 4 d
5 5 e
$ b但是,如果我在一个函数中尝试这样做,它会将所有内容都转换为新值:
changeLevel1 < - function(x){
levels(x)[which(levels(x)=='a')] < - 'missing'
}
df1 $ fact1< - changeLevel1(df1 $ fact1)
> df1
id fact1
1 1缺少
2 2缺少
3 3缺少
4 4缺少
5 5缺少
正确的解决方法是什么?
解决方案您需要返回完整的对象
x
,而不仅仅是您的赋值结果(这是字符串缺少$ c $
changeLevel1 < - function(x){
levels(x)[which(levels( x)=='a')]< - '缺少'
return(x)
}
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?
解决方案you need to return the full object
x
rather than just the result of your assignment (which is the stringmissing
).changeLevel1 <- function(x){ levels(x)[which(levels(x) == 'a')] <- 'missing' return (x) }
这篇关于R:更改函数内的级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文