【问题标题】:Group individuals with the identical rows将具有相同行的个人分组
【发布时间】:2016-08-14 18:58:02
【问题描述】:

我正在处理包含 10.000 个人的数据。数据有 8 个二进制 (0, 1) 变量。每个变量 是调查模块是否存在 == 1 == 0 的指标。总体而言,每个变量有 2^8 = 256 种可能的 0 和 1 组合,并且 每个人都是可能的。

目标:我想将具有相同行的个人分组(这意味着参加相同模块的个人)。

我的数据看起来像下面的例子,只有三个变量:

# 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

【问题讨论】:

  • interaction(dat[-1], drop=TRUE)
  • 你不能只使用with(dat, v1 + 2 * v2 + 4 * v3)作为分组变量吗?
  • 谢谢@user20650!!!这很有帮助,而且是一个非常简单的解决方案!

标签: r grouping unique rows


【解决方案1】:

我会为此推荐来自“data.table”的.GRP

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

【讨论】:

    猜你喜欢
    • 2020-01-30
    • 2020-06-26
    • 2019-05-10
    • 1970-01-01
    • 2021-09-12
    • 2023-01-06
    • 1970-01-01
    • 2021-03-01
    • 2022-07-07
    相关资源
    最近更新 更多