Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract the level from a factor

I have a factor instrumentF:

> instrumentF
[1] Guitar Drums  Cello  Harp  
Levels: Cello Drums Guitar Harp

Let's say I extract one level of this factor using [].

> level2 = instrumentF[1]
> level2
[1] Guitar
Levels: Cello Drums Guitar Harp

How I can get the factor label Guitar from the factor object level2?

level2$level doesn't seem to work:

> Error in level2$level : $ operator is invalid for atomic vectors
like image 622
dB' Avatar asked Jun 23 '15 21:06

dB'


People also ask

How do you identify the levels of a factor?

The number of levels of a factor or independent variable is equal to the number of variations of that factor that were used in the experiment. If an experiment compared the drug dosages 50 mg, 100 mg, and 150 mg, then the factor "drug dosage" would have three levels: 50 mg, 100 mg, and 150 mg.

What is a level factor?

Factor levels are all of the values that the factor can take (recall that a categorical variable has a set number of groups). In a designed experiment, the treatments represent each combination of factor levels. If there is only one factor with k levels, then there would be k treatments.

How do you find the factor level in R?

We can check if a variable is a factor or not using class() function. Similarly, levels of a factor can be checked using the levels() function.

What is the difference between factor and level?

Factor: a categorical explanatory variable. Levels: values of a factor. Treatment: a particular combination of values for the factors.


1 Answers

Convert to character, see this example:

# factor variable example
instrumentF <- as.factor(c("Guitar", "Drums", "Cello", "Harp"))

instrumentF
# [1] Guitar Drums  Cello  Harp  
# Levels: Cello Drums Guitar Harp

as.character(instrumentF)[ 1 ]
# [1] "Guitar"

See relevant post: Convert data.frame columns from factors to characters

Or subset the level:

# as levels are sorted alphabetically, we need to subset the 3rd one
levels(instrumentF)[ 3 ]
# [1] "Guitar"
like image 78
zx8754 Avatar answered Sep 20 '22 17:09

zx8754