[英]Change multi categorical factor in R to binary
I have an R factor in with 11 categories 我有11个类别的R因子
> predictor <- factor(V14)
> summary(predictor)
0 1 2 3 4 5 6 7 8 9 10
1017 20 20 20 20 20 20 20 20 20 20
I want to turn everything that is not 0 to 1. So it should look like this 我想将所有非0的值都设为1。因此它应该看起来像这样
> summary(predictor)
0 1
1017 200
Try converting to numeric: 尝试转换为数字:
predictor <- factor(+(!!V14))
summary(predictor)
# 0 1
#1017 200
Explanation 说明
The long way is factor(as.numeric(as.logical(V14))
. When numbers are coerced to logical, any number that is not zero, coerces to TRUE
and 0's will be FALSE
. Then turning it back to numbers from logical, any TRUE
will become 1
, and FALSE
will be coerced to 0
. 长途是
factor(as.numeric(as.logical(V14))
。当数字被强制转换为逻辑时,任何非零的数字都将被强制转换为TRUE
和0为FALSE
,然后将其从逻辑转换回数字,任何TRUE
将变为1
,而FALSE
将被强制为0
。
Data 数据
V14 <- c(rep(0, 1017), rep(1:10, each=20))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.