Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert factor to original numeric value

Tags:

r

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
like image 945
Eric Green Avatar asked Dec 16 '15 21:12

Eric Green


People also ask

How to convert a factor to a numerical vector?

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.

How to convert factor to numeric in R?

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 ...

How to handle the factor-to-integer conversion?

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.

How to convert factors to numbers or text in MySQL?

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:


1 Answers

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"
like image 200
Ven Yao Avatar answered Sep 21 '22 04:09

Ven Yao