簡體   English   中英

轉換為R中一年中的日期和時間

[英]Convert to the day and time of the year in R

我有超過3年的數據。 每年我都希望找到與當年的Jaunary 1相對應的那一天。 例如:

> x <- c('5/5/2007','12/31/2007','1/2/2008')
> #Convert to day of year (julian date) –
> strptime(x,"%m/%d/%Y")$yday+1
[1] 125 365   2

我想知道如何做同樣的事情,但增加時間。 但我仍然沒有時間。 誰能建議用日期和時間找到朱利安日期的更好方法是什么?

> x1 <- c('5/5/2007 02:00','12/31/2007 05:58','1/2/2008 16:25')
> #Convert to day of year (julian date) –
> strptime(x1,"%m/%d/%Y %H:%M")$yday+1
[1] 125 365   2

而不是這個結果,我想要十進制天的輸出。 例如,第一個例子是125.0833333 ,依此類推。

非常感謝。

您是否希望將一天中的數字部分作為輸出? 如果是這樣,這樣的東西將起作用:

test <- strptime(x1,"%m/%d/%Y %H:%M")

(test$yday+1) + (test$hour/24) + (test$min/(24*60))
#[1] 125.083333 365.248611   2.684028

雖然這符合你的要求,但我認為刪除+1會更有意義:

(test$yday) + (test$hour/24) + (test$min/(24*60))
#[1] 124.083333 364.248611   1.684028

雖然我的蜘蛛般的感覺刺痛,Dirk會出現並告訴我如何使用POSIXct日期/時間表示來做到這一點。

以下是使用基本函數嘗試這樣的答案:

mapply(julian, as.POSIXct(test), paste(format(test,"%Y"),"01","01",sep="-"))
#[1] 124.083333 364.248611   1.684028

您還可以使用POSIXctPOSIXlt表示沿firstof從功能xts

x1 <- c("5/5/2007 02:00", "12/31/2007 05:58", "1/2/2008 16:25")
x1
## [1] "5/5/2007 02:00"   "12/31/2007 05:58" "1/2/2008 16:25"  


y <- as.POSIXlt(x1, format = "%m/%d/%Y %H:%M")

result <- mapply(julian, x = as.POSIXct(y), origin = firstof(y$year + 1900))

result
## [1] 124.083333 364.248611   1.684028

如果你不想使用xts那么也許是這樣的

result <- mapply(julian, 
                 x = as.POSIXct(x1, format = "%m/%d/%Y %H:%M", tz = "GMT"),
                 origin = as.Date(paste0(gsub(".*([0-9]{4}).*", "\\1", x1), 
                                         "-01-01"),
                                  tz = "GMT"))

result
## [1] 124.083333 364.248611   1.684028

暫無
暫無

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

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