[R] control the conversion of factor to numeric

Martin Batholdy batholdy at googlemail.com
Tue Oct 18 15:40:27 CEST 2011


Ok, I think that would work – thanks!

However, in my case I read a data.frame via read.table().
So some of the columns get transformed to factors automatically – 
I don't generate the factor-variables as in the example, so I can't control how the levels are ordered (or can I?).



On 18.10.2011, at 15:35, R. Michael Weylandt wrote:

> Add levels= to your factor() call.
> 
> E.g.,
> 
> x1 <- factor(rep(1:4, 5), labels=c("slightly disagree", "disagree",
> "agree", "slightly agree"), levels = c(2,1,4,3))
> as.numeric(x1)
> [1] 2 1 4 3 2 1 4 3 2 1 4 3 2 1 4 3 2 1 4 3
> 
> Michael
> 
> On Tue, Oct 18, 2011 at 7:35 AM, Martin Batholdy
> <batholdy at googlemail.com> wrote:
>> 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!
>> 
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>> 



More information about the R-help mailing list