Create a vector with the Levels of a factor in r

3

I have a column in my data array 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

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

However, I can not separate it.
Is there any easy way to do this?

    
asked by anonymous 25.04.2018 / 23:05

2 answers

5

You can simplify the @WillianVieira code. In the following code, unique , only levels is not used to directly extract 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
    
26.04.2018 / 11:36
5

You can use the unique() function:

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"
    
25.04.2018 / 23:20