在 R 中查找两个日期之间的月数
在本文中,我们将讨论如何在 R 编程语言中查找两个日期之间的月数。
例子:
Input: Date_1 = 2020/02/21
Date_2 = 2020/03/21
Output: 1
Explanation: In Date_1 and Date_2 have only one difference in month.
这里我们将使用seq()函数来获取结果。此函数用于在 Vector 中创建元素序列。它将值之间的长度和差异作为可选参数。
Syntax: length(seq(from=date_1, to=date_2, by=’month’)) -1
Where: seq is function generates a sequence of numbers, from is starting date, to is ending date.
示例 1:在下面的示例中,我们将两个日期存储在两个不同的变量中,并通过使用 length(seq(from=date_1, to=date_2, by='month')) 我们找到这两个日期之间的月份数.
R
# creating date_1 variable and storing date in it.
date_1<-as.Date("2020-08-10")
# creating date_2 variable and storing date in it.
date_2<-as.Date("2020-10-10")
# Here first date will start from 2020-08-10 and
# end by 2020-10-10.Here increment is done by month.
# This three dates will be generated as we used
# seq and this dates will be stored in a.
a = seq(from = date_1, to = date_2, by = 'month'))
# Here we are finding length of a and we are subtracting
# 1 because we dont need to include current month.
length(a)-1
R
# creating date_1 variable and storing date in it.
date_1<-as.Date("2020-01-23")
# creating date_2 variable and storing date in it.
date_2<-as.Date("2020-9-25")
# Here first date will start from 2020-01-23
# and end by 2020-9-25.Here increment is done
# by month.This three dates will be generated
# as we used seq and this dates will be stored in a.
a=seq(from = date_1, to = date_2, by = 'month'))
# Here we are finding length of a and we are
# subtracting 1 because we dont need to include
# current month.
length(a)-1
输出:
2
示例 2:检查不同的日期。
电阻
# creating date_1 variable and storing date in it.
date_1<-as.Date("2020-01-23")
# creating date_2 variable and storing date in it.
date_2<-as.Date("2020-9-25")
# Here first date will start from 2020-01-23
# and end by 2020-9-25.Here increment is done
# by month.This three dates will be generated
# as we used seq and this dates will be stored in a.
a=seq(from = date_1, to = date_2, by = 'month'))
# Here we are finding length of a and we are
# subtracting 1 because we dont need to include
# current month.
length(a)-1
输出:
8