r - 给定月份中每一天的一年中的某一天
问题描述
我想month2doty()
在 R 中有一个函数,如果提供了一个代表一个月的数字(例如2
二月),则返回一个向量,其中包含该月每一天的一年32, 33, 34, …, 59
中的某一天(二月也是如此):
> month2doty(2)
[1] 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
我的世界不存在闰年。我在下面提供了一个可能的答案,但我确定有更好的解决方案吗?
解决方案
这是在基础 R 中执行此操作的另一种方法。我们在月初和下个月之间创建一个长度为 2 的序列,然后生成它们之间的所有日期。我们使用%j
informat
来显示这些日期的一年中的哪一天。
month2doty <- function(x) {
days <- seq(as.Date(paste0(format(Sys.Date(), "%Y"), "-", x, "-01")),
by = "1 month", length.out = 2)
as.integer(format(seq(days[1], days[2] - 1, by = "day"), "%j"))
}
month2doty(2)
# [1] 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
# 54 55 56 57 58 59
month2doty(12)
# [1] 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
# 354 355 356 357 358 359 360 361 362 363 364 365
seq
或仅使用一次days_in_month
的另一种变体lubridate
library(lubridate)
month2doty <- function(x) {
days <- as.Date(paste0(format(Sys.Date(), "%Y"), "-", x, "-01"))
as.integer(format(seq(days, days + days_in_month(x) - 1, by = "day"), "%j"))
}
如果我们不想区别对待闰年,我们可以硬编码年份(如在 OP 中)
month2doty <- function(x) {
days <- seq(as.Date(paste0("2015-", x, "-01")), by = "1 month", length.out = 2)
as.integer(format(seq(days[1], days[2] - 1, by = "day"), "%j"))
}
和
month2doty <- function(x) {
days <- as.Date(paste0("2015-", x, "-01"))
as.integer(format(seq(days, days + days_in_month(x) - 1, by = "day"), "%j"))
}
推荐阅读
- android - 解锁手机并将应用程序置于前台
- r - 条形图标签不匹配
- javascript - react-hook-form 的问题 - api 获取空值
- python - 如何修复崩溃程序循环
- flutter - 无法解析flutter项目中的gradle插件
- php - 为什么 $_GET 不在 nginx 服务器中工作,但在 XAMPP localhost 中工作?
- r - 估计变量中相同值的置信区间
- select - 使用 AWK 从文件 2 中使用 obs.# 从文件 2 中选择记录
- powershell - 以用户自己的语言打印成功/完成消息
- multidimensional-array - 在将 pycharm 与 python 3.6 解释器一起使用时出现意外错误,我记得在 3.7 中进行此操作,当时没有发生错误