Levels in R Programming

I myself have been teaching R for several weeks. I came across some kind of problem that I do not understand. Therefore, if I say

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

I get

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

I get to this point. What I do not get is if I say

levels(fert)[fert]

I get

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

what is the definition fert. I do not understand what logic is with this topic [fert].

+4
source share
1 answer

You have factor, I assume, therefore:

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

Factors are stored as sequential numbers with labels, for example:

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"
+7
source

Source: https://habr.com/ru/post/1627241/


All Articles