我目前正在尝试在R中对此进行编码。我想使用%Y-%m-%d(例如:2017-12-31)格式的日期作为日期,并将其转换为一年中的某一天。但是,我希望始终将02/28视为第59天,并将03/01视为第61天。如果不是a年,它将跳过#60。这样,01/01始终是#1,而12/31始终是#366。

我已经尝试过使用strftime()yday(),但是当这是year年时,两者都不会跳过第60天。根据是否是a年,它将使12/31成为第365天或#366天。

如果有人对我如何用R编写代码有任何见解,那将是很棒的!非常感谢。

file <- read.table("PATHTOMYFILE", fill = TRUE, header = TRUE)
file <- file[-c(1), ]
file$datetime <- as.Date(as.character(file$datetime))
file <- file[which(file$datetime <= as.Date("2017-09-30")), ]
file$x <- file[, 4]
file$x <- as.numeric(as.character(file$x))

# Year-day function
yearday <- function(d){
# Count previous months
yd <- ifelse(lubridate::month(d) > 1, sum(lubridate::days_in_month(1:
(lubridate::month(d)-1))), 0)

# Add days so far in month & extra day if after February
yd <- yd + lubridate::day(d) + ifelse(lubridate::month(d)>2, 1, 0)
yd
}

file$Day <- yearday(as.Date((file$datetime), format = "%Y-%m-%d"))

最佳答案

您可以使用lubridateleap_year函数。例如。,

> library(lubridate)
>
> dates <- c(as.Date("2017-12-31"), as.Date("2016-12-31"))
>
> y <- as.Date("2016-12-31")
> z <- as.Date("2017-12-31")
>
> leap_every_year <- function(x) {
+
+   ifelse(yday(x) > 59 & leap_year(x) == FALSE, yday(x) + 1, yday(x))
+
+ }
>
> leap_every_year(y)
[1] 366
> leap_every_year(z)
[1] 366
> leap_every_year(dates)
[1] 366 366

编辑:看到这与@MDEWITT的解决方案非常相似,但是它使用lubridate代替。虽然类似的想法。祝你好运!

关于r - 用leap年计算一年中的天数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54946395/

10-10 12:34