Convert coefficient to original numeric value

I don't know why I'm struggling with this because there seem to be numerous SO answers that address this question. But I am here.

Convert the vector 1 and 0 to a coefficient and name 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 

Answers to questions about the conversion of factors to numerical values ​​are shown by 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 
+5
source share
2 answers

The simplest solution is to change how you indicate that the call factor is such that it can work with any number of numerical levels.

 fact <- factor(c(1,1,0,1,0,1, 2), levels=c(0,1, 2), labels=c("no", "yes", "maybe")) as.numeric(fact) - 1 
0
source
 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 fact levels are a symbolic symbol. as.numeric(as.character(fact)) does not do this work.

 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" 
+2
source

Source: https://habr.com/ru/post/1238430/


All Articles