グループ別の集計

R の data.table によるデータ操作

Matt Dowle, Arun Srinivasan

Instructors, DataCamp

`by` 引数

by 引数を使うと、by で指定した列の一意の値ごとに集計が可能です

# How many trips happened from each start_station?
ans <- batrips[, .N, by = "start_station"]
head(ans, 3)
          start_station        N
San Francisco City Hall     2145
 Embarcadero at Sansome    12879
      Steuart at Market    11579
R の data.table によるデータ操作

`by` 引数

by 引数には、列名の character ベクトルと変数・式の list の両方を指定できます

# Same as batrips[, .N, by = "start_station"]
ans <- batrips[, .N, by = .(start_station)]
head(ans, 3)
          start_station        N
San Francisco City Hall     2145
 Embarcadero at Sansome    12879
      Steuart at Market    11579
R の data.table によるデータ操作

`by` 引数

グループ化列をその場でリネームできます

ans <- batrips[, .(no_trips = .N), by = .(start = start_station)]
head(ans, 3)
                  start   no_trips
San Francisco City Hall       2145
 Embarcadero at Sansome      12879
      Steuart at Market      11579
R の data.table によるデータ操作

`by` 内の式

by 内の list() または .() を使うと、グループ化変数をその場で計算できます

# Get number of trips for each start_station for each month
ans <- batrips[ , .N, by = .(start_station, mon = month(start_date))]
head(ans, 3)
          start_station mon    N
San Francisco City Hall   1  193
 Embarcadero at Sansome   1  985
      Steuart at Market   1  813
R の data.table によるデータ操作

では、練習しましょう!

R の data.table によるデータ操作

Preparing Video For Download...