Tổng hợp nâng cao

Xử lý dữ liệu với data.table trong R

Matt Dowle, Arun Srinivasan

Instructors, DataCamp

Ôn tập

# Ví dụ giống như trước
## Dạng LHS := RHS
batrips[, c("is_dur_gt_1hour", "week_day") := 
            .(duration > 3600, wday(start_date)]
# Giống trên, nhưng ở dạng hàm `:=`()
batrips[, `:=`(is_dur_gt_1hour = duration > 3600,
               week_day = wday(start_date))]
# Cập nhật theo tham chiếu với by
batrips[, n_zip_code := .N, by = zip_code]
Xử lý dữ liệu với data.table trong R

Thêm nhiều cột theo tham chiếu theo nhóm

# Dạng hàm
batrips[, `:=`(end_dur_first = duration[1], 
               end_dur_last  = duration[.N]),
        by = end_station]

# Dạng LHS := RHS batrips[, c("end_dur_first", "end_dur_last") := list(duration[1], duration[.N]), by = end_station]
batrips[1:5]
   trip_id duration ...        end_station ... end_dur_first end_dur_last 
    139545      435 ...    Townsend at 7th ...           435          660
    139546      432 ...    Townsend at 7th ...           435          660
    139547     1523 ...    Beale at Market ...          1523          229
    139549     1620 ... Powell Street BART ...          1620          540
    139550     1617 ... Powell Street BART ...          1620          540
Xử lý dữ liệu với data.table trong R

Phân nhóm giá trị (binning)

Với mỗi tổ hợp start_station và end_station duy nhất, nếu median duration:

  • nhỏ hơn 600: "short"
  • từ 600 đến 1800: "medium"
  • ngược lại: "long"
Xử lý dữ liệu với data.table trong R

Biểu thức nhiều dòng trong j

batrips[, trip_category := {
             med_dur = median(duration, na.rm = TRUE)
             if (med_dur < 600) "short"
             else if (med_dur >= 600 & med_dur <= 1800) "medium"
             else "long"
           },
        by = .(start_station, end_station)]
batrips[1:3]
trip_id duration ... zip_code trip_category
 139545      435 ...    94612         short
 139546      432 ...    94107         short
 139547     1523 ...    94112         short
Xử lý dữ liệu với data.table trong R

Cách làm khác

bin_median_duration <- function(dur) {
  med_dur <- median(dur, na.rm = TRUE)
  if (med_dur < 600) "short"
  else if (med_dur >= 600 & med_dur <= 1800) "medium"
  else "long"
}

batrips[, trip_category := bin_median_duration(duration), 
           by = .(start_station, end_station)]
Xử lý dữ liệu với data.table trong R

Kết hợp i, j và by

batrips[duration > 500, min_dur_gt_500 := min(duration), 
           by = .(start_station, end_station)]
batrips[1:3]
trip_id duration ... zip_code min_dur_gt_500
 139545      435 ...    94612             NA
 139546      432 ...    94107             NA
 139547     1523 ...    94112            502
Xử lý dữ liệu với data.table trong R

Cùng luyện tập nào!

Xử lý dữ liệu với data.table trong R

Preparing Video For Download...