当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


R forcats fct_recode 手动更改因子水平


手动更改因子水平

用法

fct_recode(.f, ...)

参数

.f

因子(或字符向量)。

...

< dynamic-dots > 命名字符向量序列,其中名称给出新级别,值给出旧级别。未另行提及的级别将保持原样。可以通过将级别命名为 NULL 来删除级别。

例子

x <- factor(c("apple", "bear", "banana", "dear"))
fct_recode(x, fruit = "apple", fruit = "banana")
#> [1] fruit bear  fruit dear 
#> Levels: fruit bear dear

# If you make a mistake you'll get a warning
fct_recode(x, fruit = "apple", fruit = "bananana")
#> Warning: Unknown levels in `f`: bananana
#> [1] fruit  bear   banana dear  
#> Levels: fruit banana bear dear

# If you name the level NULL it will be removed
fct_recode(x, NULL = "apple", fruit = "banana")
#> [1] <NA>  bear  fruit dear 
#> Levels: fruit bear dear

# Wrap the left hand side in quotes if it contains special variables
fct_recode(x, "an apple" = "apple", "a bear" = "bear")
#> [1] an apple a bear   banana   dear    
#> Levels: an apple banana a bear dear

# When passing a named vector to rename levels use !!! to splice
x <- factor(c("apple", "bear", "banana", "dear"))
levels <- c(fruit = "apple", fruit = "banana")
fct_recode(x, !!!levels)
#> [1] fruit bear  fruit dear 
#> Levels: fruit bear dear
源代码:R/recode.R

相关用法


注:本文由纯净天空筛选整理自Hadley Wickham等大神的英文原创作品 Change factor levels by hand。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。