Create a vector with the Levels of a factor in r

Asked

Viewed 221 times

3

I have a column in my data matrix as follows:
> as.factor(matriz$especime) [1] 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 [29] 3 3 5 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 [57] 7 7 7 7 7 7 8 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9 9 9 9 10 [85] 10 10 10 10 10 10 11 11 11 11 11 13 13 13 13 13 15 15 46 Levels: 1 2 3 5 6 7 8 9 10 11 13 15

And I need the Levels vector, that is:
1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 13, 15
For it is not a complete sequence, it lacks some numbers.

But I can’t separate it.
Is there any easy way to do this?

2 answers

5


You can simplify the code of @Willianvieira. In the following code is not used unique, only levels to directly extract the factor levels.
I’ll use the same data example.

x <- as.factor(rep(1:13, 4))

as.numeric(levels(x))
[1]  1  2  3  4  5  6  7  8  9 10 11 12 13

5

You can use the function unique():

x <- as.factor(rep(1:13, 4))
x
# [1] 1  2  3  4  5  6  7  8  9  10 11 12 13 1  2  3  4  5  6  7  8  9  10 11 12
# [26] 13 1  2  3  4  5  6  7  8  9  10 11 12 13 1  2  3  4  5  6  7  8  9  10 11
# [51] 12 13
# Levels: 1 2 3 4 5 6 7 8 9 10 11 12 13

levs <- as.numeric(unique(x))
levs
# [1]  1  2  3  4  5  6  7  8  9 10 11 12 13

class(levs)
# [1] "numeric"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.