我有我正在使用的以下資料集
dt <- data.table(RequestTime = c("2011-01-01 07:00:42","2011-01-02 05:00:47","2011-01-03 07:05:02","2011-01-04 04:00:42","2011-01-05 02:00:11"), ExportTime = c("2011-01-01 07:00:50","2011-01-05 05:00:52","2011-01-01 07:06:33","2011-03-04 04:00:51","2011-01-06 02:00:22"))
由于我正在處理日期,因此使用以下方法將兩列轉換為正確的格式:
dt$RequestTime <- as.POSIXct(dt$RequestTime)
dt$ExportTime <- as.POSIXct(dt$ExportTime)
如果開始日期和 RequestTime 之間的差異小于 86400 秒(24 小時),我正在嘗試使用 ifelse 條件陳述句根據條件更新 ExportTime 的值,然后我保持 ExportTime 相同,但如果差異更大超過 86400 秒,則第二個條件適用。這是我如何去做的。
x <- dt$RequestTime
y <- dt$ExportTime
start_date <- as.Date("2011-01-01")
dt$ExportTime <- fifelse((difftime(start_date, x, units = "secs") < 86400), y,
y - (difftime(start_date, x, units = "secs")))
所以在這種情況下,只有 5 個觀察中的 1 個應該保持不變。但是當我運行它時,我看到所有的觀察結果都保持不變。任何幫助,將不勝感激)
uj5u.com熱心網友回復:
原因是引數應該被轉換,否則它們都會變成否定的
> difftime(start_date, x, units = "secs")
Time differences in secs
[1] -46842 -126047 -219902 -295242 -374411
> difftime(start_date, x, units = "secs") < 86400
[1] TRUE TRUE TRUE TRUE TRUE
> difftime(x, start_date, units = "secs") < 86400
[1] TRUE FALSE FALSE FALSE FALSE
IE
dt$ExportTime <- fifelse((difftime( x, start_date, units = "secs") < 86400), y,
y - (difftime(start_date, x, units = "secs")))
-輸出
> dt
RequestTime ExportTime
1: 2011-01-01 07:00:42 2011-01-01 07:00:50
2: 2011-01-02 05:00:47 2011-01-06 16:01:39
3: 2011-01-03 07:05:02 2011-01-03 20:11:35
4: 2011-01-04 04:00:42 2011-03-07 14:01:33
5: 2011-01-05 02:00:11 2011-01-10 10:00:33
與原版對比
> dt
RequestTime ExportTime
1: 2011-01-01 07:00:42 2011-01-01 07:00:50
2: 2011-01-02 05:00:47 2011-01-05 05:00:52
3: 2011-01-03 07:05:02 2011-01-01 07:06:33
4: 2011-01-04 04:00:42 2011-03-04 04:00:51
5: 2011-01-05 02:00:11 2011-01-06 02:00:22
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/344225.html
