Rのデータフレームにおいて、ファクター列を2値に変換する方法をお伝えいたします。
方法はとても単純で、データフレームの列ごとにファクター型かどうかをチェックし、ファクター型であればファクターごとに2値の列を新たに作成し追加します。
ソースコードは以下のようになります。
convertFactorToBinary <- function(df, sep = ".") {
l <- list()
for (i in 1:ncol(df)) {
if ("factor" %in% class(df[[i]]) &&
!("ordered" %in% class(df[[i]]))) {
m <- sapply(levels(df[[i]]), function(x)
as.integer(x == df[[i]]))
for (j in 1:ncol(m)) {
l[[paste(colnames(df)[i], colnames(m)[j], sep = sep)]] <- m[, j]
}
} else{
l[[colnames(df)[i]]] <- df[[i]]
}
}
return(data.frame(l))
}
データセットwarpbreaksを用いて実際に試してみます。
まずは、データセットの内容を確認します。
> data("warpbreaks")
> print(str(warpbreaks))
'data.frame': 54 obs. of 3 variables:
$ breaks : num 26 30 54 25 70 52 51 26 67 18 ...
$ wool : Factor w/ 2 levels "A","B": 1 1 1 1 1 1 1 1 1 1 ...
$ tension: Factor w/ 3 levels "L","M","H": 1 1 1 1 1 1 1 1 1 2 ...
> print(head(warpbreaks))
breaks wool tension
1 26 A L
2 30 A L
3 54 A L
4 25 A L
5 70 A L
6 52 A L
次に、ファクター型の列を変換してみます。
> res <- convertFactorToBinary(warpbreaks, sep = "_") > print(str(res))
'data.frame': 54 obs. of 6 variables:
$ breaks : num 26 30 54 25 70 52 51 26 67 18 ...
$ wool_A : int 1 1 1 1 1 1 1 1 1 1 ...
$ wool_B : int 0 0 0 0 0 0 0 0 0 0 ...
$ tension_L: int 1 1 1 1 1 1 1 1 1 0 ...
$ tension_M: int 0 0 0 0 0 0 0 0 0 1 ...
$ tension_H: int 0 0 0 0 0 0 0 0 0 0 ...
> print(head(res))
breaks wool_A wool_B tension_L tension_M tension_H
1 26 1 0 1 0 0
2 30 1 0 1 0 0
3 54 1 0 1 0 0
4 25 1 0 1 0 0
5 70 1 0 1 0 0
6 52 1 0 1 0 0
ファクター列が2値になっていることが確認できました。
R データフレームのファクター列を2値に変換する方法