假設我有以下資料集:
library(data.table)
library(lubridate)
store_DT <- data.table(date = seq.Date(from = as.Date("2019-10-01"),
to = as.Date("2019-10-05"),
by = "day"),
store = c(rep("A",5),rep("B",5)))
date store
1: 2019-10-01 A
2: 2019-10-02 A
3: 2019-10-03 A
4: 2019-10-04 A
5: 2019-10-05 A
6: 2019-10-01 B
7: 2019-10-02 B
8: 2019-10-03 B
9: 2019-10-04 B
10: 2019-10-05 B
這只是一個存盤 x 日期觀察的 data.table。
假設我有另一個員工開始和結束時間(包括)的 data.table:
roster_DT <- data.table(
store = c("A", "A", "A", "A", "B", "B","B", "B"),
employee_ID = 1:8,
start_date = c("2019-09-30", "2019-10-02", "2019-10-03", "2019-10-04",
"2019-09-30", "2019-10-02", "2019-10-03", "2019-10-04"),
end_date = c("2019-10-04", "2019-10-04", "2019-10-05", "2019-10-06",
"2019-10-04", "2019-10-04", "2019-10-05", "2019-10-06")
)
store employee_ID start_date end_date
1: A 1 2019-09-30 2019-10-04
2: A 2 2019-10-02 2019-10-04
3: A 3 2019-10-03 2019-10-05
4: A 4 2019-10-04 2019-10-06
5: B 5 2019-09-30 2019-10-04
6: B 6 2019-10-02 2019-10-04
7: B 7 2019-10-03 2019-10-05
8: B 8 2019-10-04 2019-10-06
我想要做的只是簡單地計算每個商店在任何給定日期的員工人數,并將其帶回store_DT. 這里的復雜之處在于roster_DT指定了一個日期范圍。現在,一種解決方案是簡單地roster_DT使用此處的建議進行擴展。但實際資料集相當大,擴展效率不高/不可行。所以我想知道是否還有其他方法。
我正在尋找的最終資料集是:
date store employees
1: 2019-10-01 A 1
2: 2019-10-02 A 2
3: 2019-10-03 A 3
4: 2019-10-04 A 4
5: 2019-10-05 A 2
6: 2019-10-01 B 1
7: 2019-10-02 B 2
8: 2019-10-03 B 3
9: 2019-10-04 B 4
10: 2019-10-05 B 2
我的資料集中有很多商店,很多員工,所以我希望有一個 data.table 解決方案。
非常感謝!
uj5u.com熱心網友回復:
請在下面找到使用lubridate庫和庫foverlaps()功能的解決方案(reprex)data.table。
正品
- 代碼
library(data.table)
library(lubridate)
# Convert 'start_date' and 'end_date' columns into class 'date'
sel_cols <- c("start_date", "end_date")
roster_DT[, (sel_cols) := lapply(.SD, ymd), .SDcols = sel_cols]
# Create a dummy variable in the data.table 'store_DT'
store_DT[, dummy := date]
# Set keys for the data.table 'roster_DT'
setkey(roster_DT, start_date, end_date)
# Merge the two data.tables with 'foverlaps()' and summarize the resulting data.table to get the requested data.table (i.e. 'Results')
Results <- foverlaps(store_DT,roster_DT, by.x=c("date", "dummy"), type = "within")[, dummy := NULL][,.(employees = .N/2), by = .(date, store)][]
# Reorder the data.table 'Results' by 'store', then 'date'
setorder(Results, store, date)
-輸出
Results
#> date store employees
#> 1: 2019-10-01 A 1
#> 2: 2019-10-02 A 2
#> 3: 2019-10-03 A 3
#> 4: 2019-10-04 A 4
#> 5: 2019-10-05 A 2
#> 6: 2019-10-01 B 1
#> 7: 2019-10-02 B 2
#> 8: 2019-10-03 B 3
#> 9: 2019-10-04 B 4
#> 10: 2019-10-05 B 2
由reprex 包(v2.0.1)于 2021 年 11 月 17 日創建
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/358121.html
上一篇:資料框中從長格式到寬格式
下一篇:從r中的資料集中洗掉尾隨的0和1
