Reputation: 19
I have to convert this class to True and False
Class : Factor w/ 2 levels "benign","malignant": 1 1 1 1 1 2 1 1 1 1
I already tried it to convert it to a numeric, by
as.numeric(BreastCancer$Class)
as.integer(BreastCancer$Class)
then I did
as.logical(BreastCancer$Class)
but I only get NA's.
I tried to use the install packages dplyr
for recoding, but I can not figure out how that works.
Upvotes: 2
Views: 1020
Reputation: 2864
It is important to keep track of what you are coding as TRUE
or FALSE
:
vec_factor <- factor(
c(1, 1, 1, 1, 1, 2, 1, 1, 1, 1),
labels = c("benign", "malignant")
)
str(vec_factor)
# Factor w/ 2 levels "benign","malignant": 1 1 1 1 1 2 1 1 1 1
vec_logical <- as.logical(as.integer(vec) == 1)
str(vec_logical)
# logi [1:10] TRUE TRUE TRUE TRUE TRUE FALSE ...
Update:
As @zx8754 commented, as.logical
is redundant:
str(as.integer(vec) == 1)
# logi [1:10] TRUE TRUE TRUE TRUE TRUE FALSE ...
and @李哲源's answer is much more elegant.
Upvotes: 1
Reputation: 56219
Maybe simply:
BreastCancer$ClassLogical <- BreastCancer$Class == "benign"
Upvotes: 0