- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
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 create a new level using unique levels of a factor in R data frame?
To create a new level using unique levels of a factor in R data frame, we can follow the below steps −
- First of all, create a data frame with factor column.
- Then, create a new level for the unique values in the factor column using table and levels function.
Create the data frame
Let's create a data frame as shown below −
> Factor<-factor(sample(LETTERS[1:15],20,replace=TRUE)) > df<-data.frame(Factor) > df
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
Factor 1 O 2 D 3 K 4 M 5 C 6 M 7 K 8 F 9 L 10 H 11 E 12 N 13 O 14 E 15 G 16 H 17 E 18 K 19 K 20 F
Create new level using unique values in factor column
Using levels function with table function to create new level for unique values in the factor column subsetting the column with single square brackets −
> Factor<-factor(sample(LETTERS[1:15],20,replace=TRUE)) > df<-data.frame(Factor) > levels(df[,1])[table(df[,1])==1]<-"New_Level" > df
Output
Factor 1 O 2 New_Level 3 K 4 M 5 New_Level 6 M 7 K 8 F 9 New_Level 10 H 11 E 12 New_Level 13 O 14 E 15 New_Level 16 H 17 E 18 K 19 K 20 F
- Related Articles
- How to make duplicate factor levels unique in an R data frame?
- How to create a subset for a factor level in an R data frame?
- How to create scatterplot for factor levels in an R data frame?
- How to drop factor levels in subset of a data frame in R?
- How to collapse factor levels in an R data frame?
- How to combine the levels of a factor variable in an R data frame?
- How to convert numeric levels of a factor into string in R data frame?
- How to extract the factor levels from factor column in an R data frame?
- How to set a level of a factor column in an R data frame to NA?
- How to create a new column for factor variable with changed factor levels by using mutate of dplyr package in R?
- Extract a particular level from factor column in an R data frame.
- How to find the cumulative sum for factor levels in an R data frame?
- How to create boxplot with multiple factor levels using ggplot2 in R?
- How to select the first row for each level of a factor variable in an R data frame?
- How to create table of two factor columns in an R data frame?

Advertisements