- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 extract unique values in multiple columns in an R data frame using a single line code?
To extract unique values in multiple columns in an R data frame, we first need to create a vector of the column values but for that we would need to read the columns in matrix form. After that we can simply unique function for the extraction. To understand how it works check out the below examples.
Consider the below data frame −
Example
x1<-rpois(20,2) x2<-rpois(20,5) x3<-rpois(20,2) df1<-data.frame(x1,x2,x3) df1
Output
x1 x2 x3 1 1 4 3 2 2 3 2 3 1 6 1 4 1 6 1 5 2 4 2 6 2 4 0 7 1 5 1 8 3 5 2 9 3 7 3 10 1 2 2 11 2 6 3 12 2 3 1 13 3 6 0 14 2 4 7 15 1 6 1 16 0 4 0 17 1 2 2 18 4 3 1 19 1 4 1 20 3 7 2
Extracting unique values in df1 −
Example
df1<-as.vector(as.matrix(df1)) unique(df1)
Output
[1] 1 2 3 0 4 6 5 7
Example
y1<-rpois(20,10) y2<-rpois(20,20) y3<-rpois(20,5) df2<-data.frame(y1,y2,y3) df2
Output
y1 y2 y3 1 8 24 5 2 5 19 2 3 8 17 1 4 10 21 5 5 8 27 3 6 12 14 5 7 8 19 3 8 11 26 10 9 11 25 5 10 6 20 7 11 4 26 3 12 7 21 6 13 14 21 3 14 11 18 7 15 11 13 6 16 7 17 5 17 9 21 7 18 5 20 6 19 16 24 7 20 8 14 1
Extracting unique values in df2 −
Example
df2<-as.vector(as.matrix(df2)) unique(df2)
Output
[1] 8 5 10 12 11 6 4 7 14 9 16 24 19 17 21 27 26 25 20 18 13 2 1 3
- Related Articles
- How to convert multiple columns into single column in an R data frame?
- How to remove outliers from multiple boxplots created with the help of boxplot function for columns of a data frame using single line code in R?
- How to extract a single column of an R data frame as a data frame?
- How to extract unique combination of rows in an R data frame?
- How to extract columns of a data frame in R using dplyr package?
- How to change a data frame with comma separated values in columns to multiple columns in R?
- How to make all values in an R data frame unique?
- How to multiply row values in a data frame having multiple rows with single row data frame in R?
- How to extract data frame columns stored in a list in R?
- How to extract only factor columns name from an R data frame?
- How to extract columns based on particular column values of an R data frame that match a pattern?
- How to find the unique values in a column of an R data frame?
- How to extract unique combinations of two or more variables in an R data frame?
- How to convert columns of an R data frame into a single vector?
- How to create an ID column for the combination of values in multiple columns in R data frame?

Advertisements