R 的 data.table 資料操作
Matt Dowle, Arun Srinivasan
Instructors, DataCamp
by 參數可針對 by {{1}} 中指定的(分組)欄位,每個唯一值分別計算。
# 每個 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
by 參數可接受欄名的 character 向量,或變數/運算式的 list
# 等同於 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
可即時重新命名分組欄位
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
by 中的 list() 或 .() 運算式可即時計算分組變數
# 取得每月、每個 start_station 的行程數
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 資料操作