How to extract unique values in multiple columns in an R data frame using a single line code?

R ProgrammingServer Side ProgrammingProgramming

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

 Live Demo

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

 Live Demo

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
raja
Published on 06-Feb-2021 08:19:17
Advertisements