[R] control the conversion of factor to numeric

David Winsemius dwinsemius at comcast.net
Tue Oct 18 15:50:42 CEST 2011


On Oct 18, 2011, at 7:35 AM, Martin Batholdy 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?

I think you want to first change the ordering of the levels and then  
convert as desired.

 > levels(x) <- c("slightly disagree", "disagree", "slightly agree",  
"agree")
 > x
  [1] slightly disagree disagree          slightly agree    agree
  [5] slightly disagree disagree          slightly agree    agree
  [9] slightly disagree disagree          slightly agree    agree
[13] slightly disagree disagree          slightly agree    agree
[17] slightly disagree disagree          slightly agree    agree
Levels: slightly disagree disagree slightly agree agree

#  Now choose hoe to convert

 > as.numeric(x)
  [1] 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4
 > as.character(x)
  [1] "slightly disagree" "disagree"          "slightly agree"     
"agree"
  [5] "slightly disagree" "disagree"          "slightly agree"     
"agree"
  [9] "slightly disagree" "disagree"          "slightly agree"     
"agree"
[13] "slightly disagree" "disagree"          "slightly agree"    "agree"
[17] "slightly disagree" "disagree"          "slightly agree"    "agree"
>
>
>
> 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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list