如何计算R中两个日期之间的天数?
在本文中,我们将讨论如何在 R 编程语言中查找两个日期之间的天数。
例子:
Input:
Date_1 = 2020/03/21
Date_2 = 2020/03/22
Output: 1
Explanation: In Date_1 and Date_2 have only one difference in day.So output will be 1.
这里我们将使用 seq()函数来获取结果。此函数用于在 Vector 中创建元素序列。要获得天数,length()函数与 seq() 作为参数一起使用。
Syntax: length(seq(from=date_1, to=date_2, by=’day’)) -1
Parameter:
- seq is function generates a sequence of numbers.
- from is starting date.
- to is ending date.
- by is step, increment.
示例 1:
R
# creating date_1 variable
# and storing date in it.
date_1<-as.Date("2020-10-10")
# creating date_2 variable
# and storing date in it.
date_2<-as.Date("2020-10-11")
.
a = seq(from = date_1, to = date_2, by = 'day')
# Here we are finding length of
# a and we are subtracting 1 because
# we dont need to include current day.
length(a)-1
R
# creating date_1 variable
# and storing date in it.
date_1<-as.Date("2020-01-10")
# creating date_2 variable
# and storing date in it.
date_2<-as.Date("2020-02-20")
a = seq(from = date_1, to = date_2, by = 'day')
# Here we are finding length of a
# and we are subtracting 1 because we
# dont need to include current day.
length(a)-1
输出:
示例 2:
电阻
# creating date_1 variable
# and storing date in it.
date_1<-as.Date("2020-01-10")
# creating date_2 variable
# and storing date in it.
date_2<-as.Date("2020-02-20")
a = seq(from = date_1, to = date_2, by = 'day')
# Here we are finding length of a
# and we are subtracting 1 because we
# dont need to include current day.
length(a)-1
输出:
41