Reputation: 36547
How do I get the mode of the underlying values in a factor? For example, given test2 below, how would I get "character" instead of "numeric"?
test = c( "a" , "b" , "c" )
mode( test ) # "character"
test2 = factor( test )
mode( test2 ) # "numeric"
Upvotes: 2
Views: 5551
Reputation: 5700
The mode function returns the storage mode. Factors are stored internally as integers (numeric) and have levels (the "a","b","c" in your example). The levels are characters. A common idiom with factors is to coerce them to character, which does this:
> as.character.factor
function (x, ...)
levels(x)[x]
<environment: namespace:base>
Upvotes: 3
Reputation: 368181
Use
mode(levels(test2))
to test the factor's levels rather than values.
You can think of a factor as a hashed or keyed variable: you simply get numerical indices that you'd use to index in the map from numeric value to textual labels. In that view, it is clear that you wanted to test the mode of the labels rather than values.
Upvotes: 4