[R] control the conversion of factor to numeric

Martin Batholdy batholdy at googlemail.com
Tue Oct 18 13:35:45 CEST 2011


Dear R-list,



I currently have to convert a data.frame with several factor-variables to a numeric matrix.

Now the problem is, that the order of the factor-labels don't match the order I would like to use.


for example, let's assume I have this factor-variable in my data-frame:

x <- factor(rep(1:4, 5), labels=c("slightly disagree", "disagree", "agree", "slightly agree"))


Now I would like to convert this to a numeric vector so that disagree == 1, slightly disagree == 2, slightly agree == 3, and agree gets the value 4.
but as.numeric(x) just converts the factor levels to numerical values according to their label-order.


Is there a convenient, flexible function that let's you control how the factor-levels get converted to numerical values?



thanks for any suggestions!



More information about the R-help mailing list