정지수
정지수

Reputation: 53

levels in R Programming

I am self teaching R for few weeks now. I came across some problem I don't understand. So if I say

fert <- as.factor(c(50,20,10,10,20,50))
levels(fert)

I get

[1] "10" "20" "50"

I get until this point. What I don't get is if I say

levels(fert)[fert]

I get

"50" "20" "10" "10" "20" "50"

which is the definition of fert. I don't understand what the logic is with this [fert]thing.

Upvotes: 4

Views: 98

Answers (1)

thelatemail
thelatemail

Reputation: 93843

You have a factor i'm presuming, so:

fert <-  factor(c(50,20,10,10,20,50))
levels(fert)
#[1] "10" "20" "50"

Factors are stored as sequential numbers with labels, like:

as.numeric(fert)
#[1] 3  2  1  1  2  3
#  corresponding to the labels of:
#   50 20 10 10 20 50

So, since:

levels(fert)[c(3,2,1,1,2,3)]
#[1] "50" "20" "10" "10" "20" "50"

then,

levels(fert)[fert]
#[1] "50" "20" "10" "10" "20" "50"

Upvotes: 7

Related Questions