使用 .SD(I)
.SD 搭配 .SDcols 是非常强大的功能,可大幅简化对多列的计算。
.SD是一个特殊符号,表示 Subset of Data(数据子集)。.SDcols指定应包含在.SD中的列。
本练习是课程的一部分
在 R 中使用 data.table 进行数据处理
练习说明
- 针对每个月,找到对应最短行程的行(在
duration上使用which.min())。 - 结果应包含
month、start_station、end_station、start_date、end_date和duration列。
交互式实操练习
通过完成这段示例代码来试试这个练习。
relevant_cols <- c("start_station", "end_station",
"start_date", "end_date", "duration")
# Find the row corresponding to the shortest trip per month
shortest <- batrips[, ___,
by = month(start_date),
.SDcols = ___]
shortest