當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。