Change the reference level for the variable in R

I have a dataset (let's call it DATA) with a COLOR variable. COLOR mode is numeric, and class is a factor. Firstly, I am a little confused by the β€œnumeric” one - when printed, the data for COLOR is not numeric - they are all symbol values ​​such as white or blue or black, etc. Any clarifications on this subject are appreciated.

In addition, I need to write the R-code to return the levels of the COLOR variable, then determine the current reference level of this variable and finally set the reference level of this variable to white. I tried using the coefficient, but was completely unsuccessful.

Thanks for taking the time to help.

+4
source share
2 answers

mode(DATA$COLOR) is "numeric" because R internally stores factors in the form of numeric codes (to save space) plus the associated vector of labels corresponding to the code values. When you print the coefficient, R automatically replaces the corresponding label for each code.

 f <- factor(c("orange","banana","apple")) ## [1] orange banana apple ## Levels: apple banana orange str(f) ## Factor w/ 3 levels "apple","banana",..: 3 2 1 c(f) ## strip attributes to get a numeric vector ## [1] 3 2 1 attributes(f) ## $levels ## [1] "apple" "banana" "orange" ## $class ## [1] "factor" 

... I need to write R code to return the levels of the COLOR variable ...

 levels(DATA$COLOR) 

... then determine the current reference level of this variable,

 levels(DATA$COLOR)[1] 

... and finally set the reference level of this variable to white.

 DATA$COLOR <- relevel(DATA$COLOR,"White") 
+6
source

This is a consequence of how R stores factors . The values ​​that you see on the console look like characters, but are stored internally as numbers (for reasons that are likely to go beyond).

If you want to restore levels, you can enter levels(DATA$COLOR) . Take a look at the ?factor and ?levels in the console to see more. If you want to reinstall the factor, try adding a reproducible example so that I can go through the code.

+3
source

All Articles