如何计算 R 中日期之间的年数?
在本文中,我们将讨论如何在 R 编程语言中计算两个日期之间的年数或年差。
例子:
Input:
Date_1 = 2020/02/21
Date_2 = 2023/03/21
Output:
3
Explanation:
In Date_1 and Date_2 have three years difference in year.
这里我们将使用 seq()函数来获取结果。此函数用于在 Vector 中创建元素序列。
句法:
length(seq(from=date_1, to=date_2, by=’year’)) -1
示例 1:
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("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
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("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
输出:
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