I don't know why I'm struggling with this because there seem to be numerous SO answers that address this question. But here I am.
I convert a vector of 1's and 0's to a factor and label the values "yes" and "no".
fact <- factor(c(1,1,0,1,0,1),
levels=c(1,0),
labels=c("yes", "no"))
#[1] yes yes no yes no yes
#Levels: yes no
The answers to questions about converting factors back to numeric values suggest as.numeric(as.character(x))
and as.numeric(levels(x)[x]
.
as.numeric(as.character(fact))
#[1] NA NA NA NA NA NA
as.numeric(levels(fact))[fact]
#[1] NA NA NA NA NA NA
Converting a Factor that is a Number: If the factor is number, first convert it to a character vector and then to numeric. If a factor is a character then you need not convert it to a character. And if you try converting an alphabet character to numeric it will return NA.
There are two steps for converting factor to numeric: Step 1: Convert the data vector into a factor. The factor() command is used to create and modify factors in R. Step 2: The factor is converted into a numeric vector using as.numeric(). When a factor is converted into a numeric vector, the numeric codes corresponding to the factor levels will ...
There's nothing to handle the factor-to-integer (or numeric) conversion because it's expected that as.integer (factor) returns the underlying integer codes (as shown in the examples section of ?factor ). It's probably okay to define this function in your global environment, but you might cause problems if you actually register it as an S3 method.
The factor accepts only a restricted number of distinct values. It is helpful in categorizing data and storing it on multiple levels. At times you require to explicitly change factors to either numbers or text. To achieve this, one has to use the functions as.character () or as.numeric (). There are two steps for converting factor to numeric:
fact <- factor(c(1,1,0,1,0,1),
levels=c(1,0),
labels=c("yes", "no"))
fact
# [1] yes yes no yes no yes
# Levels: yes no
levels(fact)
# [1] "yes" "no"
Now, the levels of fact
is a character vector. as.numeric(as.character(fact))
is in no way to do the job.
c(1, 0)[fact]
# [1] 1 1 0 1 0 1
Update:
unclass(fact)
# [1] 1 1 2 1 2 1
# attr(,"levels")
# [1] "yes" "no"
mode(fact)
# [1] "numeric"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With