如何在 r 中按日期范围进行子定义(带有示例)


在 R 中按日期范围子定义数据框的最简单方法是使用以下语法:

 df[df$date >= " some date " & df$date <= " some date ", ]

本教程提供了该功能实际使用的几个示例。

示例 1:两个日期之间的子集

以下代码显示如何在数据框中选择两个包含日期之间的行:

 #make this example reproducible
set.seed(0)

#create data frame
df <- data.frame(date = as . Date (" 2021-01-01 ") - 0:19,
                 sales = runif (20, 10, 500) + seq (50, 69)^2)

#view first six rows
head(df)

        dirty date
1 2021-01-01 2949,382
2 2020-12-31 2741.099
3 2020-12-30 2896.341
4 2020-12-29 3099.698
5 2020-12-28 3371.022
6 2020-12-27 3133.824

#subset between two dates, inclusive
df[df$date >= " 2020-12-25 " & df$date <= " 2020-12-28 ", ]

        dirty dates
5 2020-12-28 3371.022
6 2020-12-27 3133.824
7 2020-12-26 3586.211
8 2020-12-25 3721.891

只需修改上方和下方的符号即可选择两个独占日期之间的线:

 #make this example reproducible
set.seed(0)

#create data frame
df <- data.frame(date = as . Date (" 2021-01-01 ") - 0:19,
                 sales = runif (20, 10, 500) + seq (50, 69)^2)

#subset between two dates, exclusive
df[df$date > " 2020-12-25 " & df$date < " 2020-12-28 ", ]

        dirty date
6 2020-12-27 3133.824
7 2020-12-26 3586.211

示例 2:特定日期之后的子集

以下代码显示如何选择数据框中出现在特定日期之后的行:

 #make this example reproducible
set.seed(0)

#create data frame
df <- data.frame(date = as . Date (" 2021-01-01 ") - 0:19,
                 sales = runif (20, 10, 500) + seq (50, 69)^2)

#subset after a certain date
df[df$date >= " 2020-12-22 ", ]

         dirty dates
1 2021-01-01 2949.382
2 2020-12-31 2741.099
3 2020-12-30 2896.341
4 2020-12-29 3099.698
5 2020-12-28 3371.022
6 2020-12-27 3133.824
7 2020-12-26 3586.211
8 2020-12-25 3721.891
9 2020-12-24 3697.791
10 2020-12-23 3799.266
11 2020-12-22 3640.275

示例 3:某个日期之前的子集

以下代码显示如何从数据框中选择特定日期之前发生的行:

 #make this example reproducible
set.seed(0)

#create data frame
df <- data.frame(date = as . Date (" 2021-01-01 ") - 0:19,
                 sales = runif (20, 10, 500) + seq (50, 69)^2)

#subset before a certain date
df[df$date < " 2020-12-22 ", ]

         dirty date
12 2020-12-21 3831.928
13 2020-12-20 3940.513
14 2020-12-19 4315.641
15 2020-12-18 4294.211
16 2020-12-17 4612.222
17 2020-12-16 4609.873
18 2020-12-15 4850.633
19 2020-12-14 5120.034
20 2020-12-13 4957.217

其他资源

如何在 R 中绘制时间序列
如何从R中的日期中提取年份
如何在R中将每日数据聚合为月度和年度数据

添加评论

您的电子邮箱地址不会被公开。 必填项已用*标注