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
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.
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.
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.
Factor: a categorical explanatory variable. Levels: values of a factor. Treatment: a particular combination of values for the factors.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With