R语言 如何计算日期之间的年数
在这篇文章中,我们将讨论如何用R编程语言计算两个日期之间的年数或年差。
例子 。
输入 。
Date_1 = 2020/02/21
日期_2 = 2023/03/21
输出 。
3
解释 。
在Date_1和Date_2中,年份相差3年。
这里我们将使用seq()函数来得到结果。这个函数是用来创建一个向量中的元素序列的。
语法 。
length(seq(from=date_1, to=date_2, by=’year’))-1
例1 :
# 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("2023-10-10")
# Here first date will start from
# 2020-08-10 and end by 2023-10-10.
# Here increment is done by year.
# This three dates will be generated
# as we used eq and this dates will
# be stored in a.
a = seq(from = date_1, to = date_2, by = 'year')
# Here we are finding length of a and
# we are subtracting 1 because we dont
# need to include current year.
length(a)-1
输出 。
3
例2 :
# 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("2100-08-10")
# Here first date will start from
# 2020-08-10 and end by 2100-08-10.
# Here increment is done by year.
# 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 = 'year')
# Here we are finding length of a and
# we are subtracting 1 because we dont
# need to include current year.
length(a)-1
输出 。
80