按组计算

在 R 中使用 data.table 进行数据处理

Matt Dowle, Arun Srinivasan

Instructors, DataCamp

by 参数

by 参数可针对 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 参数

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
在 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().() 表达式可即时计算分组变量

# 计算每月每个 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 进行数据处理

开始练习!

在 R 中使用 data.table 进行数据处理

Preparing Video For Download...