我試圖讓我現有的觀察在 R 中間隔 10 分鐘。
我這樣做了:
data3$date= ceiling_date(as.POSIXct(data3$betdate), unit = "10 minutes")
data3 %>% group_by(date, prov) %>%
summarise(cant=n())
但是這段代碼的問題在于,如果沒有觀察到某個區間,則該區間將不會出現在輸出資料中,這很有意義,因為在該區間內沒有日期的觀察。所以我需要捕獲關于沒有記錄觀察的間隔的資訊。有任何想法嗎?已經謝謝大家了。
uj5u.com熱心網友回復:
查看@Limey 評論的簡化示例,僅使用幾個月和data.table
# set up fake data
set.seed(1000)
library(lubridate)
# create sequence, and save it as a data.frame so it has a header
months <- seq(ymd("2022-01-01"), ymd("2022-06-01"), by = "month")
# create fake data, and remove some rows
dat <- data.frame(month = months, values = sample(100:200, length(months)))
dat <- dat[-sample(1:length(months),3),]
dat
# month values
#1 2022-01-01 167
#4 2022-04-01 150
#6 2022-06-01 128
在這里,我們執行合并并查看代表缺失觀測值的 NA
library(data.table)
setDT(dat)
months_listed <- data.frame(month = seq(min(dat$month), max(dat$month), by = "month"))
setDT(months_listed)
merge.data.table(months_listed, dat, by = "month", all.x = T)
# month values
#1: 2022-01-01 167
#2: 2022-02-01 NA
#3: 2022-03-01 NA
#4: 2022-04-01 150
#5: 2022-05-01 NA
#6: 2022-06-01 128
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/514683.html
