2016-08-14 3 views
4

10.000 명의 개인을 포함하는 데이터로 작업하고 있습니다. 데이터에는 8 개의 이진 (0, 1) 변수가 있습니다. 각 변수 은 설문 모듈이 == 1 또는 == 0이 아닌 경우 표시기입니다. 전체적으로 각 변수에 대해 2^8 = 256 개의 가능한 조합이 0과 1이며 각각은 입니다.동일한 행을 가진 개인을 그룹화하십시오.

목표 : 동일한 행 (동일한 모듈에 참여한 개인을 의미 함)을 가진 개인을 그룹화하고자합니다.

내 데이터가 onlye 세 개의 변수와 다음의 예처럼 보이는 :이은 "data.table"에서 .GRP을 권하고 싶습니다

# 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

'상호 작용 (DAT [-1 ], drop = TRUE)' – user20650

+0

그룹핑 변수로'with (dat, v1 + 2 * v2 + 4 * v3)'를 사용할 수 없습니까? –

+1

Thanks @ user20650 !!! 그게 도움이되고 아주 쉬운 해결책입니다! – maller

답변

0

:

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 
관련 문제