- Trending Categories
- Data Structure
- Operating System
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to extract the factor levels from factor column in an R data frame?
To extract the factor levels from factor column, we can simply use levels function. For example, if we have a data frame called df that contains a factor column defined with x then the levels of factor levels in x can be extracted by using the command levels(df$x). This extraction is helpful if we have a large number of levels.
Consider the below data frame −
x1<−factor(sample(letters[1:3],20,replace=TRUE)) y1<−rnorm(20,5,0.31) df1<−data.frame(x1,y1) df1
x1 y1 1 a 4.480255 2 b 4.865971 3 a 5.278760 4 a 5.208462 5 c 4.815111 6 a 5.116731 7 a 5.278687 8 b 5.832620 9 c 5.182383 10 a 4.741525 11 b 4.645954 12 c 4.972552 13 a 5.515956 14 c 4.951365 15 b 5.214277 16 c 5.444890 17 b 4.590310 18 a 4.949908 19 a 4.858476 20 c 5.179366
Extracting factor levels of x1 −
 "a" "b" "c"
If the column values are not recorded as factor level but they represent them then we need to use as.factor with the column as shown in the below example −
x2<−sample(c("Hot","Cold","Warm"),20,replace=TRUE) y2<−rpois(20,30) df2<−data.frame(x2,y2) df2
x2 y2 1 Warm 29 2 Hot 23 3 Cold 26 4 Hot 30 5 Hot 36 6 Hot 25 7 Hot 34 8 Hot 24 9 Warm 29 10 Hot 34 11 Warm 25 12 Cold 26 13 Hot 30 14 Cold 31 15 Warm 28 16 Cold 25 17 Cold 32 18 Hot 25 19 Hot 32 20 Cold 28
 "Cold" "Hot" "Warm"
- Extract a particular level from factor column in an R data frame.
- How to collapse factor levels in an R data frame?
- How to extract only factor columns name from an R data frame?
- How to find the sum by distinct column for factor levels in an R data frame?
- How to create scatterplot for factor levels in an R data frame?
- How to make duplicate factor levels unique in an R data frame?
- How to combine the levels of a factor variable in an R data frame?
- How to find the cumulative sum for factor levels in an R data frame?
- How to sort a numerical factor column in an R data frame?
- How to drop factor levels in subset of a data frame in R?
- How to find the most frequent factor value in an R data frame column?
- How to convert numeric levels of a factor into string in R data frame?
- How to subset factor columns in an R data frame?
- How to find the column means by factor levels in R?
- How to add a new column in an R data frame with count based on factor column?