
390
15
章 データの前処理
レシピ
15.10
ファクタのレベル名を変更する
問題
ファクタのレベル名を変更したい。
解決策
forcats
パッケージの
fct_recode()
を使います。
sizes <- factor(c( "small", "large", "large", "small", "medium"))
sizes
#> [1] small large large small medium
#> Levels: large medium small
#
マッピングの名前付きベクトルを渡す
fct_recode(sizes, S = "small", M = "medium", L = "large")
#> [1] S L L S M
#> Levels: L M S
解説
元レベルと新レベルの
2
ベクトルを使いたい場合には、
do.call()
を
fct_recode()
と使います。
old <- c("small", "medium", "large")
new <- c("S", "M", "L")
#
まずは、
old
と
new
をマッピングする名前付きベクトルを作る
mappings <- setNames(old, new)
mappings
#> S M L
#> "small" "medium" "large"
# fct_recode
に渡す引数リストを作る
args <- c(list(sizes), mappings)
#
リストの構造を確認
str(args)
#> List of 4
#> $ : Factor ...