Friday, June 3, 2011

Creating Factors

reorder is fantastic to change the order of factors. If you import some data which contains a factor the factor levels are ordered according to the alphabet. This is also the sequence shown in graphics. So the levels "good", "better", "best" are displayed in reverse order.

Here are some examples showing how to create an ordered factor (in the order you want) out of an other:

if you have a numeric vector - and you want to label it
> taste <- rep(0:2,c(5,5,5)) # create the numeric vector > taste
[1] 0 0 0 0 0 1 1 1 1 1 2 2 2 2 2
# make a factor out auf it
> taste <- factor(taste, levels=0:2, labels=c("good","better","best"))

> taste
[1] good good good good good better better better better better
[11] best best best best best
Levels: good better best

> taste <- rep(0:2,5) # different use of rep

> taste
[1] 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2

> taste <- factor(taste, levels=0:2, labels=c("good","better","best"))

> taste
[1] good better best good better best good better best good
[11] better best good better best
Levels: good better best

> taste <- letters[rep(1:3,5)] # create a vector containing characters/strings

> taste
[1] "a" "b" "c" "a" "b" "c" "a" "b" "c" "a" "b" "c" "a" "b" "c"

> taste <- factor(taste, levels=c("c","b","a"), labels=c("good","better","best"))

> taste
[1] best better good best better good best better good best
[11] better good best better good
Levels: good better best


there is also gl
> my.factor <- gl(number.of.levels,number.of.replications,labels=c(.....))
e.g.

> my.factor <- gl(3,4,labels=c("yes","maybe","no"))

> my.factor
[1] yes yes yes yes maybe maybe maybe maybe no no no no
Levels: yes maybe no

No comments :

Post a Comment