target <- c(1,0,1,0,1,1)
target %>% as.factor(levels = c("false", "true"))
Error in as.factor(., levels = c("false", "true")) :
unused argument (levels = c("false", "true"))
如何将矢量目标转换为1对应于true而0对应于false的因子?
答案 0 :(得分:1)
target <- c(1,0,1,0,1,1)
factor(target == 1)
# [1] TRUE FALSE TRUE FALSE TRUE TRUE
# Levels: FALSE TRUE
另一种方式:
factor( target, levels = c(0, 1), labels = c(FALSE, TRUE) )
# [1] TRUE FALSE TRUE FALSE TRUE TRUE
# Levels: FALSE TRUE
将数字强制转换为逻辑类型:
factor(as.logical(target))
# [1] TRUE FALSE TRUE FALSE TRUE TRUE
# Levels: FALSE TRUE
答案 1 :(得分:1)
这是另一个转折......只需重命名levels(target)
。以下是您的数据:
> target <- as.factor(c(1,0,1,0,1,1))
> levels(target)
[1] "0" "1"
确保按照与原始levels(target)
:
> levels(target) <- c("FALSE","TRUE")
> target
[1] TRUE FALSE TRUE FALSE TRUE TRUE
Levels: FALSE TRUE