[R] control the conversion of factor to numeric

Philipp Pagel p.pagel at gmx.net
Tue Oct 18 16:02:31 CEST 2011


On Tue, Oct 18, 2011 at 03:40:27PM +0200, Martin Batholdy wrote:
> 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?).


You can't while reading the data but nothing can stop you from
re-ordering the levels once you have your data.frame. An example with
the iris data:

> data(iris)
> str(iris)
'data.frame':   150 obs. of  5 variables:
 $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
 $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
 $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
 $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
 $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
> iris$Species <- factor(iris$Species, ordered=TRUE, levels=c('versicolor', 'virginica', 'setosa'))
> str(iris)
'data.frame':   150 obs. of  5 variables:
 $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
 $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
 $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
 $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
 $ Species     : Ord.factor w/ 3 levels "versicolor"<"virginica"<..: 3 3 3 3 3 3 3 3 3 3 ...

cu
	Philipp



More information about the R-help mailing list