r - 循环将年份分为两部分
问题描述
我正在寻找一种方法来创建一个循环,该循环将多年划分为开始部分和结束部分,并给出数值与发生切割的年份的百分比。在我更详细地描述之前,向您展示我想要获得的产品可能是最简单的:
在下一次迭代开始之前,循环的第一次迭代会给我以下输出:
beginning_section = c("2003-01-01/2003-02-01","2004-01-01/2004-02-01","2005-01-01/2005-02-01")
ending_section = c("2003-02-02/2003-12-31","2004-02-02/2004-12-31","2005-02-02/2005-12-31")
time_scale = c(0.169,0.169,0.169)
在下一次迭代开始之前,循环的第二次迭代将为我提供以下输出:
beginning_section = c("2003-01-01/2003-02-02","2004-01-01/2004-02-02","2005-01-01/2005-02-02")
ending_section = c("2003-02-03/2003-12-31","2004-02-03/2004-12-31","2005-02-03/2005-12-31")
time_scale = c(0.172,0.172,0.172)
在循环结束之前,循环的最后一次迭代将为我提供以下输出:
beginning_section = c("2003-01-01/2003-11-30","2004-01-01/2004-11-30","2005-01-01/2005-11-30")
ending_section = c("2003-02-03/2003-12-31","2004-02-03/2004-12-31","2005-02-03/2005-12-31")
time_scale = c(0.915,0.915,0.915)
#do some calculations with beginning_section, ending section, and time scaled
基本上,它应该将所有年份在特定月日点划分为两个字符向量(一个用于所有开始部分,一个用于所有结束部分)并给出一个整数向量,它显示一年中的百分比剪下来了。例如,如果削减发生在年中,那么截止将是 0.5。然后循环应该向前移动一天并再次执行相同的操作,依此类推。
到目前为止,我已经尝试过(并且失败了绝对悲惨):
library(tidyverse)
days <- 1:30 %>% as.character()
months <- 2:11 %>% as.character()
years <- 2003:2017 %>% as.character()
beg_section <- NULL
end_section <- NULL
time_scaled <- NULL
for (m in months) {
for (d in days) {
for (y in years) {
temp_beg <- paste(y, "-1-1/", y, "-", m, "-", d, sep = "")
beg_section <- rbind(beg_section,temp_beg)
temp_end <- paste(y, "-", m, "-", d, "/", y, "-12-31", sep = "")
end_section <- rbind(end_section,temp_end)
temp_scale <- (as.numeric(m) + as.numeric(d)/30 - 1) / 12
time_scaled <- rbind(time_scaled,temp_scale)
}
}
}
beg_section <- beg_section %>% as.vector()
end_section <- end_section %>% as.vector()
time_scaled <- time_scaled %>% as.vector()
n <- 1
m <- length(years) %>% as.numeric()
while (m < length(beg_section)) {
lead_up_period <- beg_section[n:m]
end_period <- end_section[n:m]
vol_adjustment <- time_scaled[n]
print(lead_up_period)
print(end_period)
print(vol_adjustment)
n <- m + 1
m <- m + length(years)
}
#end
我还想指出,解决方案不必绝对完美。例如,如果所有月份只处理 30 天,那将非常感激。
解决方案
推荐阅读
- php - WordPress:使用 meta_queries 对多个帖子类型进行单一查询?
- python - GroupByKey 的光束类型提示
- android - Kotlin 和 Room 的 Dagger 2 错误
- linux-kernel - D中的内核模块
- python - 如何将 pyqtgraph IsocurveItem 实例与空绘图轴(而不是 ImageItem)对齐?
- android - 小于 21 的 API 级别中 translationZ 的 XML 替代
- python - Keras ImageDataGenerator 不同的图像
- r - 游戏周围的预测间隔
- java - 如何在所有 Java 类中使用 RabbitTemplate
- bash - Bash自定义功能更改目录