Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

levels in R Programming

Tags:

r

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.

like image 530
정지수 Avatar asked Mar 14 '23 09:03

정지수


1 Answers

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"
like image 60
thelatemail Avatar answered Mar 25 '23 01:03

thelatemail