簡體   English   中英

使用R基於TimeSeries數據添加行

[英]Adding Rows based on TimeSeries Data using R

考慮以下數據集;

scd <- read.table(text = "
2019-04-01 10:00:00 | 2019-04-01 12:00:00 | 10
2019-04-02 10:00:00 | 2019-04-02 12:00:00 | 5
2019-04-03 13:00:00 | 2019-04-03 15:00:00 | 7
2019-04-04 16:00:00 | 2019-04-04 19:00:00 | 5
2019-04-05 10:00:00 | 2019-04-05 12:00:00 | 6
2019-04-06 10:00:00 | 2019-04-06 12:00:00 | 5", sep = "|")

colnames(scd) <- c('start_date_ts', 'end_date_ts', 'people_count')

上面的代碼由開始日期和結束日期以及時間組成,並假設我希望每小時在人員計數列中提到的計數增加。

例如,以第1行為例,它說從上午10點到下午12點,我預計計數會增加10。

2019-04-01 10:00:00 = 10 +實際數據

2019-04-01 11:00:00 = 10 +實際數據

2019-04-01 12:00:00 = 10 +實際數據

實際數據;

fc_data <- read.table(text = "
2019-04-01 10:00:00 | 10
2019-04-01 12:00:00 | 5
2019-04-04 19:00:00 | 5
2019-04-05 12:00:00 | 6
2019-04-06 08:00:00 | 3", sep = "|")

colnames(fc_data) <- c('pred_t', 'fpc')

我期待以下結果; (來自fc_data)

第1-10 + 10 = 20行

第2-5 + 10 = 15行

第3-5 + 5 = 10行

第4-6 + 6行= 12

第5-3 + 0 = 3行

我希望代碼遍歷每一行並與開始時間和結束時間匹配,並為我提供上面提供的輸出。

我的方法

fc_data$events_pc <- with(fc_data, ifelse(fc_data$pred_t == scd$start_date_ts | fc_data$pred_t == scd$end_date_ts &
                                        fc_data$pred_t == scd$end_date_ts,
                                      fc_data$fpc + scd$people_count, fc_data$fpc + 0))

盡管我將一些行加起來,但其他行實際上不匹配。 我已經在堆棧中搜索了一些信息,但是找不到任何信息。 任何輸入將非常有幫助。

我們可以使用mapply並將scd中的start_date_tsend_date_tspred_t ,獲得相應的people_count並將其添加到fpc

mapply(function(x, y) {
   inds <- x >= scd$start_date_ts & x <= scd$end_date_ts
   if (any(inds))  
      y + scd$people_count[inds]
   else
      y
}, fc_data$pred_t, fc_data$fpc)

#[1] 20 15 10 12  3

確保date-time變量為POSIXct格式,如果不是,則需要更改它們。

fc_data$pred_t <- as.POSIXct(fc_data$pred_t)
scd[1:2] <- lapply(scd[1:2], as.POSIXct)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM