How to find the groupwise common value for a data.table object?


To find the groupwise common value for a data.table object, we can use Reduce function with intersect function.

For example, if we have a data.table object called DT that contains a numerical column say Num and a categorical column say C where C exists at the first position then the groupwise common value can be found by using the command given below −

Reduce(intersect,DT[,.(list(unique(Num))),C]$V1)

Example

Consider the below data.table object −

Group<-sample(LETTERS[1:4],20,replace=TRUE)
Rate<-rpois(20,1)
library(data.table)
DT1<-data.table(Group,Rate)
DT1

output

The following dataframe is created −

   Group Rate
1:  A    4
2:  C    0
3:  D    0
4:  C    0
5:  A    3
6:  A    1
7:  D    1
8:  B    0
9:  A    1
10: A    0
11: C    3
12: B    2
13: B    1
14: C    2
15: D    3
16: B    1
17: A    0
18: C    1
19: A    1
20: C    1

In order to find the groupwise common value of Rate for all groups in Group column, add the following code to the above snippet −

Example

Reduce(intersect,DT1[,.(list(unique(Rate))),Group]$V1)

Output

If you execute all the above given snippets as a single program, it generates the following Output −

[1] 1 0

Example

Consider the below data.table object −

Category<-sample(c("I","II","III"),20,replace=TRUE)
Rank<-sample(1:3,20,replace=TRUE)
DT2<-data.table(Category,Rank)
DT2

output

The following dataframe is created −

  Category Rank
1:    I    1
2:  III    2
3:  III    3
4:    I    2
5:    I    3
6:  III    3
7:  III    2
8:  III    2
9:  III    2
10:  II    3
11: III    2
12:  II    1
13: III    1
14:  II    3
15:   I    1
16: III    2
17: III    1
18:  II    1
19:   I    1
20: III    3

To find the groupwise common value of Rank for all groups in Category column, add the following code to the above snippet −

Example

Reduce(intersect,DT2[,.(list(unique(Rank))),Category]$V1)

Output

If you execute all the above given snippets as a single program, it generates the following Output −

[1] 1 3

Example

Consider the below data.table object −

Class<-sample(c("First","Second","Third"),20,replace=TRUE)
Score<-sample(0:2,20,replace=TRUE)
DT3<-data.table(Class,Score)
DT3

output

The following dataframe is created −

    Class  Score
1:  First   2
2:  Second  0
3:  First   1
4:  Third   2
5:  Second  1
6:  Third   1
7:  Third   0
8:  Third   1
9:  Third   2
10: Third   1
11: Second  0
12: Third   0
13: First   2
14: First   1
15: First   1
16: First   0
17: Second  2
18: Second  2
19: First   0
20: Second  1

To find the groupwise common value of Score for all groups in Class column, add the following code to the above snippet −

Example

Reduce(intersect,DT3[,.(list(unique(Score))),Class]$V1)

Output

If you execute all the above given snippets as a single program, it generates the following Output −

[1] 2 1 0

Updated on: 02-Nov-2021

75 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements