我正在尝试将因子变量转换为二进制/布尔值(0 或 1)。
样本数据:
df <-data.frame(a = c(1,2,3), b = c(1,1,2), c = c("Rose","Pink","Red"), d = c(2,3,4))
尝试像这样转换它:a,b,IsRose,IsPink,IsRed,d
为此,我尝试了以下方法,但收效甚微。
library(ade4)
acm.disjonctif(df)
在基本 R 中,您可以使用sapply()
在水平上,使用==
检查是否存在并as.integer()
将其强制转换为二进制。
cbind(df[1:2], sapply(levels(df$c), function(x) as.integer(x == df$c)), df[4])
# a b Pink Red Rose d
# 1 1 1 0 0 1 2
# 2 2 1 1 0 0 3
# 3 3 2 0 1 0 4
但由于你有一百万行,你可能想要数据表.
library(data.table)
setDT(df)[, c(levels(df$c), "c") :=
c(lapply(levels(c), function(x) as.integer(x == c)), .(NULL))]
这使
df
# a b d Pink Red Rose
# 1: 1 1 2 0 0 1
# 2: 2 1 3 1 0 0
# 3: 3 2 4 0 1 0
如果需要,您可以重置列顺序setcolorder(df, c(1, 2, 4:6, 3))
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)