Grouping faces with equal rows

I work with data containing 10,000 people. The data contains 8 binary (0, 1) variables. Each variable is an indicator if there is a poll module == 1 or not == 0. In general, 2 ^ 8 = 256 possible combinations of 0 and 1 for each variable and each person is possible.

Purpose: I want to group people with the same lines (this means individuals who participated in the same modules).

My data looks like this with only three variables:

# example
dat <- data.frame(id = 1:8,          # unique ID
                  v1 = rep(0:1, 4),
                  v2 = rep(1:0, 4),
                  v3 = rep(1:1, 4))

# I can find the unique rows
unique(dat[ , -1])

# I also can count the number of occurence of the unique rows (as suggested by http://stackoverflow.com/questions/12495345/find-indices-of-duplicated-rows)
library(plyr)
ddply(dat[ , -1], .(v1, v2, v3), nrow)

# But I need the information of the occurence on the individual level like this:
dat$v4 <- rep(c("group1", "group2"), 4)

# The number of rows alone is not sufficient because, different combinations can be the same counting
+4
source share
1 answer

I would recommend .GRPfrom "data.table" for this:

library(data.table)
> as.data.table(dat)[, v4 := sprintf("group_%s", .GRP), .(v1, v2, v3)][]
   id v1 v2 v3      v4
1:  1  0  1  1 group_1
2:  2  1  0  1 group_2
3:  3  0  1  1 group_1
4:  4  1  0  1 group_2
5:  5  0  1  1 group_1
6:  6  1  0  1 group_2
7:  7  0  1  1 group_1
8:  8  1  0  1 group_2
0

Source: https://habr.com/ru/post/1651220/


All Articles