串联 data.table 表达式

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

Matt Dowle, Arun Srinivasan

Instructors, DataCamp

串联表达式

可以将 data.table 表达式串联使用,即 x[...][...][...]

step_1 <- batrips[duration > 3600]
step_2 <- step_1[duration > 3600][order(duration)]
step_2[1:3]
# 等价于
batrips[duration > 3600]

batrips[duration > 3600][order(duration)]
batrips[duration > 3600][order(duration)][1:3]
trip_id duration          
 295912 3601     
 347471 3602     
 536050 3602
在 R 中使用 data.table 进行数据处理

串联表达式

# 平均时长最低的三个起始站
step_1 <- batrips[, .(mn_dur = mean(duration)), by = "start_station"]
step_2 <- step_1[order(mn_dur)]
step_2[1:3]
# 平均时长最低的三个起始站
batrips[, .(mn_dur = mean(duration)),  
        by = "start_station"][order(mn_dur)][1:3]
                                 start_station   mn_dur
                                 2nd at Folsom 551.0807
 Temporary Transbay Terminal (Howard at Beale) 655.8563
                             2nd at South Park 697.7034
在 R 中使用 data.table 进行数据处理

uniqueN()

  • uniqueN() 是一个辅助函数,返回输入对象中唯一值的个数(整数)
  • 它可接收向量、data.framedata.table
id <- c(1, 2, 2, 1)
uniqueN(id)
2
x <- data.table(id, val = 1:4)
id val
 1   1
 2   2
 2   3
 1   4
uniqueN(x)
4
uniqueN(x, by = "id")
2
在 R 中使用 data.table 进行数据处理

uniqueN() 与 by 配合

按月统计唯一自行车 ID 的总数

ans <- batrips[, uniqueN(bike_id), by = month(start_date)]
head(ans, 3)
 month    V1   ## <~~ auto naming of cols
     1   605
     2   608
     3   631
在 R 中使用 data.table 进行数据处理

Vamos praticar!

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

Preparing Video For Download...