R语言 查找两个日期之间的月数
在这篇文章中,我们将讨论如何用R编程语言查找两个日期之间的月数。
例子
输入: Date_1 = 2020/02/21
Date_2 = 2020/03/21
输出: 1
解释: 在Date_1和Date_2中,只有一个月的差别。
这里我们将使用 seq() 函数来得到结果。这个函数是用来创建一个向量中的元素序列。它需要长度和值之间的差异作为可选的参数。
语法: length(seq(from=date_1, to=date_2, by=’month’)-1
其中:seq是生成数字序列的函数,from是起始日期,to是结束日期。
例1: 在下面的例子中,我们在两个不同的变量中存储了两个日期,通过使用length(seq(from=date_1, to=date_2, by=’month’))我们可以找到这两个日期之间的月数。
# 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
输出
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