R の data.table によるデータ操作
Matt Dowle, Arun Srinivasan
Instructors, DataCamp
第2引数jは列の選択(および計算)に使用します
# General form of data.table syntax
DT[i, j, by]
| | |
| | --> grouped by what?
| -----> what to do?
--------> on which rows?
j引数は列名の文字ベクトルを受け付けます
ans <- batrips[, c("trip_id", "duration")]
head(ans, 2)
trip_id duration
139545 435
139546 432
batrips_df <- as.data.frame(batrips)
ans <- batrips_df[, "trip_id"]
head(ans, 2)
# The result is a vector, not a data.frame
139545, 139546
ans <- batrips[, "trip_id"]
# Still a data.table, not a vector
head(ans, 2)
trip_id
139545
139546
列名の代わりに列番号も使用できます
ans <- batrips[, c(2, 4)]
head(ans, 2)
duration start_station
435 San Francisco City Hall
432 San Francisco City Hall
ただし、これは悪い慣行とされています
# If the order of columns changes, the result is wrong
batrips[, c(2, 4)]
# The result is always correct, no matter the order
batrips[, c("duration", "start_station")]
-c("col1", "col2", ...) で指定した列を除外する-の代わりに!を使っても同様に動作する# Select all cols *except* those shown below
ans <- batrips[, -c("start_date", "end_date", "end_station")]
head(ans, 1)
trip_id duration start_station start_terminal bike_id end_terminal
139545 435 San Francisco City Hall 58 65 473
subscription_type zip_code
Subscriber 94612
前の章でi引数において列を変数のように使用した方法を思い出してください。
# Recap the "i" argument
# All trips more than an hour
batrips[duration > 3600]
同様に、列名の変数リストを使って列を選択できます
ans <- batrips[, list(trip_id, dur = duration)]
head(ans, 2)
trip_id dur
139545 435
139546 432
単一列を選択する際、list()で囲まない場合はvectorが返されます
# Select a single column and return a data.table
ans <- batrips[, list(trip_id)]
head(ans ,2)
trip_id
139545
139546
# Select a single column and return a vector
ans <- batrips[, trip_id]
head(ans, 2)
139545 139546
.() はlist()のエイリアスです(簡略記法)
# .() is the same as list()
ans <- batrips[, .(trip_id, duration)]
head(ans, 2)
trip_id duration
139545 435
139546 432
R の data.table によるデータ操作