WoooHaaaa
WoooHaaaa

Reputation: 20440

How to get the level of a specified number in a factor?

Say, I have a factor of data(e.g. [1,2,3,4....]) :

a <- factor(data)

Now, I have a specified element in data(e.g. 1024) and I want to know its level in the factor, how do I make it ?

Upvotes: 0

Views: 597

Answers (2)

vaettchen
vaettchen

Reputation: 7659

I understand that you want to know the numerical level that is represented by the factor string. Building on @Sven Hohenstein's sample, you could get that with

a <- factor(letters[1:3])
a
[1] a b c
as.integer( a[ a == "b" ] )
[1] 2

Upvotes: 2

Sven Hohenstein
Sven Hohenstein

Reputation: 81683

I assume you are looking for drop:

> a <- factor(letters[1:3])
> a
[1] a b c
Levels: a b c
> levels(a[2, drop = TRUE])
[1] "b"

The argument drop = TRUE drops all non-present factor levels.

Upvotes: 2

Related Questions