2017-05-03 5 views
0

내 데이터는 다음과 같습니다. 행을 날짜, ID1 및 ID2로 그룹화하고자합니다. ID3에있는 행은 모두 개의 행으로 그룹화됩니다.이 행은 하위 ID가 1과 2 인 ID가 일치합니다. 또한 추가 할 통계와 생성 할 n() 통계를 나타냅니다.일부 행 (다른 행의 하위 집합)이 여러 그룹에 속하는 R에서 그룹화하는 방법은 무엇입니까?

 date  ID1  ID2  ID3 stat1 stat2 stat3 
1 12-03-07 abc123 wxy456 pqr123 10 20  30 
2 12-03-07 abc123 wxy456 pqr123 20 40  60 
3 10-04-07 bcd456 wxy456 hgf356 10 20  40 
4 12-03-07 abc123 wxy456 hfz123 30 60  90 
5 12-03-07 abc123 wxy456 <NA>  40 50  70 

원하는 출력

date  ID1,  ID2, ID3, n, stat1, stat2, stat3 
12-03-07 abc123, wxy456, pqr123, 3, 70, 110, 160 
10-04-07 bcd456, wxy456, hgf356, 1, 10, 20, 40 
12-03-07 abc123, wxy456, hfz123, 2 , 40, 50, 70 
+0

dplyr 용액 : 'DF %> % GROUP_BY (날짜, ID1, ID2, ID3) %> % 요약한다 (N = N() STAT1 = SUM (STAT1), stat2 = SUM (stat2) STAT3 = sum (stat3)' –

+0

이것은 내가 처리하고있는 솔루션과 비슷합니다. 그룹핑을 처리하는 동안 NA 열을 그룹화하지만 동일한 첫 번째 및 두 번째 열을 가진 모든 행으로 그룹화하지 않습니다. 다른 세 번째 열 – MyLeftS0ck

답변

0

아마 더 우아한 해결책을하지만 가입 후 평균 통계를 계산하여이 사용 dplyr의 GROUPBY/(아담 Quek의 코드와 같이) 요약을 해결했다.

 # Summarize 
     df <- df %>% group_by(date, ID1, ID2, ID3) %>% summarise(n=n(), stat1=sum(stat1), stat2=sum(stat2), stat3=sum(stat3) 

     # Select instances where NA 
     dfNA <- df %>% filter(is.na(ID3)) 

     # Select instances where no NA 
     df1 <- df %>% filter(!is.na(ID3)) 

     # Join these 
     dfBig <- df1 %>% full_join(dfNA, by = c("date", "ID1")) %>% 
      subset(select= c("ID1", "date", "n.x", "n.y", "stat1.x", "stat1.y", "stat2.x", "stat2.y", "stat3.x", "stat3.y")) 

     # Replace <NA>s by 0 
     dfBig$stat1.x[is.na(dfBig$stat1.x)] <- 0 
     dfBig$stat1.y[is.na(dfBig$stat1.y)] <- 0 
     dfBig$stat2.x[is.na(dfBig$stat1.x)] <- 0 
     dfBig$stat2.y[is.na(dfBig$stat1.y)] <- 0 
     dfBig$stat3.x[is.na(dfBig$stat1.x)] <- 0 
     dfBig$stat3.y[is.na(dfBig$stat1.y)] <- 0 
     dfBig$n.x[is.na(dfBig$n.x)] <- 0 
     dfBig$n.y[is.na(dfBig$n.y)] <- 0 

    # Compute Mean stats and Rename Columns 
     dfBig$stat1Mean <- (dfBig$stat1.x * dfBig$n.x + dfBig$stat1.y * dfBig$n.y)/(dfBig$n.x +dfBig$n.y) 
     dfBig$stat2Mean <- (dfBig$stat1.x * dfBig$n.x + dfBig$stat1.y * dfBig$n.y)/(dfBig$n.x +dfBig$n.y) 
     dfBig$stat3Mean <- (dfBig$stat1.x * dfBig$n.x + dfBig$stat1.y * dfBig$n.y)/(dfBig$n.x +dfBig$n.y) 
     dfBig$n2 <- dfBig$n.x + dfBig$n.y