我有一個包含 4 列的資料框,其中第一列稱為 Date_et_heure。在該列中,我有一個 POSIXct POSIXt 類日期時間,格式為“%Y-%m-%d %H:%M:%S”。我想安排我的資料框,以便行始終按時間順序排列。
我嘗試使用了arrange() 函式,但它不能接受POSIXct POSIXt 格式的資料;我總是收到錯誤:
UseMethod("arrange") 中的錯誤:沒有適用于 'arrange' 的方法應用于類 "c('POSIXct', 'POSIXt') 的物件
我嘗試使用 order() 函式,為此我需要使用 as.Date() 函式轉換 POSIXct。但是 as.Date() 忽略了列的時間 ("%H:%M:%S") 格式。
有誰知道是否有一種方法可以訂購 POSIXct 類資料?希望有一個可靠的轉換。
謝謝!
uj5u.com熱心網友回復:
POSIXct在 R 中既有用又強大。在內部,它“只是”一個double,您可以直接對它們使用所有常用操作。
這是一個最小的基本 R 演示:
> set.seed(123) # reproducible
> v <- as.POSIXct(Sys.time() rnorm(5)*3600)
> v # random draw around 'now', not sorted
[1] "2021-11-09 06:05:15.009926 CST" "2021-11-09 06:25:04.083292 CST"
[3] "2021-11-09 08:12:24.072185 CST" "2021-11-09 06:43:06.552463 CST"
[5] "2021-11-09 06:46:38.158100 CST"
> diff(v) # not sorted -> pos. and neg. differences
Time differences in mins
[1] 19.81789 107.33315 -89.29200 3.52676
>
所以這里order()用來重新排列:
> w <- v[order(v)]
> w
[1] "2021-11-09 06:05:15.009926 CST" "2021-11-09 06:25:04.083292 CST"
[3] "2021-11-09 06:43:06.552463 CST" "2021-11-09 06:46:38.158100 CST"
[5] "2021-11-09 08:12:24.072185 CST"
> diff(w)
Time differences in mins
[1] 19.81789 18.04115 3.52676 85.76523
>
這按預期安排了時間戳。
uj5u.com熱心網友回復:
發布您的代碼,錯誤訊息并不表明問題是您的物件與所提到的類,而是您為在這種??情況下碰巧具有該類的物件提供了不適用的方法。
問題不在于 dplyr 功能,如其他回復中的示例所示。
這是 POSIXlt 和 POSIXct 的示例(它們都有類“POSIXct”“POSIXt”)。您可以同時排序,也可以雙向排序。
df <- data.frame(
Date_et_heurePOSIXct = sample(seq(as.POSIXct('2021-08-01'), as.POSIXct('2021-11-09', tz = "UTC"), by = "1 sec"), 5),
Date_et_heurePOSIXlt = sample(seq(as.POSIXlt('2021-08-01'), as.POSIXlt('2021-11-09', tz = "UTC"), by = "1 sec"), 5)
)
df %>% arrange(Date_et_heurePOSIXct)
df %>% arrange(desc(Date_et_heurePOSIXct))
df %>% arrange(Date_et_heurePOSIXlt)
df %>% arrange(desc(Date_et_heurePOSIXlt))
class(df$Date_et_heurePOSIXct)
class(df$Date_et_heurePOSIXlt)
uj5u.com熱心網友回復:
雙方order并dplyr::arrange可以排序"POSIXct"的物件。
i <- order(df1$Date_et_heure)
df1[i,]
# Date_et_heure x
#1 2021-11-09 12:41:57 i
#2 2021-11-09 12:41:58 d
#3 2021-11-09 12:41:59 j
#4 2021-11-09 12:42:00 e
#5 2021-11-09 12:42:01 h
#6 2021-11-09 12:42:02 b
#7 2021-11-09 12:42:03 a
#8 2021-11-09 12:42:04 f
#9 2021-11-09 12:42:05 c
#10 2021-11-09 12:42:06 g
df1 |> dplyr::arrange(Date_et_heure)
# Date_et_heure x
#1 2021-11-09 12:41:57 i
#2 2021-11-09 12:41:58 d
#3 2021-11-09 12:41:59 j
#4 2021-11-09 12:42:00 e
#5 2021-11-09 12:42:01 h
#6 2021-11-09 12:42:02 b
#7 2021-11-09 12:42:03 a
#8 2021-11-09 12:42:04 f
#9 2021-11-09 12:42:05 c
#10 2021-11-09 12:42:06 g
測驗資料
set.seed(2021)
n <- 10
Date_et_heure <- Sys.time() sample(n)
df1 <- data.frame(Date_et_heure, x = letters[1:n])
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/354148.html
