
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Make All Values in an R Data Frame Unique
To make all values in an R data frame unique, we can use make.unique function but firstly we would need to unlist the data frame values and read them with as.character. For Example, if we have a data frame called df that contains duplicate as well as nonduplicate values then we can make all the values unique by using the below command −
df[]<-make.unique(as.character(unlist(df)))
Example 1
Following snippet creates a sample data frame −
x<-rpois(20,1) df1<-data.frame(x) df1
The following dataframe is created
x 1 0 2 0 3 1 4 1 5 1 6 0 7 2 8 0 9 1 10 0 11 0 12 0 13 1 14 2 15 1 16 1 17 0 18 0 19 1 20 1
To make all values in df1 unique on the above created data frame, add the following code to the above snippet −
x<-rpois(20,1) df1<-data.frame(x) df1[]<-make.unique(as.character(unlist(df1))) df1
Output
If you execute all the above given snippets as a single program, it generates the following Output −
x 1 0 2 0.1 3 1 4 1.1 5 1.2 6 0.2 7 2 8 0.3 9 1.3 10 0.4 11 0.5 12 0.6 13 1.4 14 2.1 15 1.5 16 1.6 17 0.7 18 0.8 19 1.7 20 1.8
Example 2
Following snippet creates a sample data frame −
y<-sample(letters[1:5],20,replace=TRUE) df2<-data.frame(y) df2
The following dataframe is created
y 1 c 2 a 3 b 4 c 5 c 6 d 7 a 8 a 9 e 10 a 11 c 12 c 13 c 14 a 15 c 16 b 17 c 18 c 19 d 20 b
To make all values in df2 unique on the above created data frame, add the following code to the above snippet −
y<-sample(letters[1:5],20,replace=TRUE) df2<-data.frame(y) df2[]<-make.unique(as.character(unlist(df2))) df2
Output
If you execute all the above given snippets as a single program, it generates the following Output −
y 1 c 2 a 3 b 4 c.1 5 c.2 6 d 7 a.1 8 a.2 9 e 10 a.3 11 c.3 12 e.1 13 c.4 14 a.4 15 c.5 16 b.1 17 c.6 18 c.7 19 d.1 20 b.2