data.table 워크플로에 조인 통합하기

R의 data.table로 데이터 결합하기

Scott Ritchie

Postdoctoral Researcher in Systems Genomics

data.table 표현식 연결

data.table 표현식은 순차적으로 연결할 수 있습니다:

demographics[...][...]

조인 연결의 일반 형식:

DT1[DT2, on][i, j, by]
    |    |   |  |  |
    |    |   |  |   --> 그룹화 기준?
    |    |   |   -----> 수행할 작업?
    |    |    --------> 대상 행?
    |     ------------> 조인 키 열
     -----------------> 조인할 data.table?
R의 data.table로 데이터 결합하기

조인 후 계산

customers <- data.table(name   = c("Mark", "Matt", "Angela", "Michelle"), 
                        gender = c("M", "M", "F", "F"), 
                        age    = c(54, 43, 39, 63))
customers
       name gender age
1:     Mark      M  54
2:     Matt      M  43
3:   Angela      F  39
4: Michelle      F  63
R의 data.table로 데이터 결합하기

조인 후 계산

purchases <- data.table(name  = c("Mark", "Matt", "Angela", "Michelle"),
                        sales = c(1, 5, 4, 3),
                        spent = c(41.70, 41.78, 50.77, 60.01))
purchases
       name sales spent
1:     Mark     1 41.70
2:     Matt     5 41.78
3:   Angela     4 50.77
4: Michelle     3 60.01
R의 data.table로 데이터 결합하기

조인 후 계산

customers[purchases, 
          on = .(name)][sales > 1, 
                        j = .(avg_spent = sum(spent) / sum(sales)), 
                        by = .(gender)] 
   gender avg_spent
1:      M  13.91333
2:      F  20.00333
R의 data.table로 데이터 결합하기

조인과 계산

조인과 함께하는 계산:

DT1[DT2, on, j]
    |    |   | 
    |    |    ----> 조인 결과에 수행할 작업?
    |     --------> 키로 사용할 열?
     -------------> 조인할 data.table?

대용량 data.table에 효율적입니다!

R의 data.table로 데이터 결합하기

조인과 열 생성

열 생성은 주 data.table에서 수행됩니다:

customers[purchases, on = .(name), return_customer := sales > 1]
customers
       name gender age return_customer
1:     Mark      M  54           FALSE
2:     Matt      M  43            TRUE
3:   Angela      F  39            TRUE
4: Michelle      F  63            TRUE
R의 data.table로 데이터 결합하기

매칭 행으로 그룹화

by = .EACHI는 DT2의 각 행을 기준으로 j를 그룹화합니다

DT1[DT2, on, j, by = .EACHI]
    |    |   |  |
    |    |   |   --> DT1의 각 매칭 행으로 그룹화
    |    |    -----> 조인 결과에 수행할 작업?
    |     ---------> 키로 사용할 열?
     --------------> 조인할 data.table?
R의 data.table로 데이터 결합하기

매칭 행으로 그룹화

shipping[customers, on = .(name), 
         j = .("# of shipping addresses" = .N),
         by = .EACHI]

R의 data.table로 데이터 결합하기

조인과 열 기반 그룹화

by의 열로 그룹화하면 계산이 주 data.table로 제한됩니다:

DT1[DT2, on, j, by]
    |    |   |  |
    |    |   |   --> DT1의 어떤 열로 그룹화?
    |    |    -----> DT1 열에 수행할 작업?
    |     ---------> 키로 사용할 열?
     --------------> 조인할 data.table?
R의 data.table로 데이터 결합하기

조인과 열 기반 그룹화

customers에서 조인 후 그룹별 계산:

customers[shipping, on = .(name), 
          .(avg_age = mean(age)), by = .(gender)]
   gender  avg_age
1:      M 46.66667
2:      F 39.00000
R의 data.table로 데이터 결합하기

연습해 봅시다!

R의 data.table로 데이터 결합하기

Preparing Video For Download...