R日期处理
提示
- 获取当前日期和时间:在 R 中,使用
Sys.Date()
获取当前日期,使用Sys.time()
获取当前系统时间(含日期和时间)。 - lubridate 包的应用:
lubridate
包提供了高效的日期处理功能,包括获取当前日期和时间、提取年、月、日、以及一次性操作多个日期值。 - 操作和更新日期值:通过
lubridate
包,可以对日期进行各种操作(如增加年、月、天),使用update()
函数一次性更新多个日期值的年、月、日。
根据我们使用 R 的目的不同,我们可能需要处理包含日期和时间的数据。
R 为我们提供了各种处理日期和时间的函数。
在 R 中获取当前系统日期和时间
在 R 中,我们使用 Sys.Date()
和 Sys.time()
分别获取基于本地系统的当前日期和时间。例如,
# 获取当前系统日期
Sys.Date()
# 获取当前系统时间
Sys.time()
输出
[1] "2022-07-11"
[1] "2022-07-11 04:16:52 UTC"
在上面的例子中,我们使用了不同的函数来获取基于本地系统的当前日期和时间。
这里,
Sys.date()
- 返回当前日期,即 2022-07-11Sys.time()
- 返回当前日期、时间和时区,即 2022-07-11 04:16:52 UTC
使用 R 的 lubridate 包
R 中的 lubridate
包使得日期值的提取和操作部分更加高效。
这个包下有各种函数可以用来处理日 期。
但首先,为了访问 lubridate
包,我们需要先导入该包:
# 访问 lubridate 包
library(lubridate)
这里,我们已经成功导入了 lubridate 包。
1. 使用 R lubridate 包获取当前日期
# 访问 lubridate 包
library(lubridate)
# 获取带有时间和时区的当前日期
now()
# 输出:"2022-07-11 04:34:23 UTC"
这里,我们使用了 lubridate
包提供的 now()
函数来获取带有时间和时区的当前日期。
2. 从多个日期值中提取年、月和日
在 R 中,我们使用 lubridate
包提供的 year()
、month()
和 mday()
函数分别从多个日期值中提取年、月和日。例如,
# 导入 lubridate 包
library(lubridate)
dates <- c("2022-07-11", "2012-04-19", "2017-03-08")
# 从日期中提取年份
year(dates)
# 从日期中提取月份
month(dates)
# 从日期中提取天数
mday(dates)
输出
[1] 2022 2012 2017
[1] 7 4 3
[1] 11 19 8
这里,
- year(dates) - 返回
dates
中的所有年份,即2022 2012 2017
- month(dates) - 返回
dates
中的所有月份,即7 4 3
- mday(dates) - 返回
dates
中的天数,即11 19 8
3. 在 R 中操作多个日期值
R 中的 lubridate 包允许我们一次性操作多个日期值。例如,
# 导入 lubridate 包
library(lubridate)
dates <- c("2022-07-11", "2012-04-19", "2017-03-08")
# 将每个年份增加一年
print(dates + years(1))
# 将每个月份增加一个月
print(dates + months(1))
# 更新天数
mday(dates) <- c(22, 18, 15)
print(dates)
输出
[1] "2023-07-11" "2013-04-19" "2018-03-08"
[1] "2022-08-11" "2012-05-19" "2017-04-08"
[1] "2022-07-22" "2012-04-18" "2017-03-15"
这里,
- dates + years(1) - 将
dates
中的每个年份增加一年 - dates + months(1) - 将
dates
中的每个月份增加一个月 - mday(dates)
<-
c(22, 18, 15) - 将dates
中的每个天数更新为新的天数。
4. 使用 update() 在 R 中更新多个日期值
在 R 中,我们可以使用 update()
函数一次性更新多个日期值。例如,
# 导入 lubridate 包
library(lubridate)
dates <- c("2022-07-11", "2012-04-19", "2017-03-08")
# 使用 update() 更新所有日期值
new_dates <- update(dates,
year = c(2022, 2015, 2019),
month = c(9, 12, 1),
day = c(21, 2, 13)
)
输出
[1] "2022-09-21" "2015-12-02" "2019-01-13"
在上面的例子中,我们使用了 update()
函数来更新包含年、月、日值的 dates
向量为新的值。
- year = c(2022, 2015, 2019) - 使用新的年份更新
dates
的当前年份。 - month = c(9, 12, 1) - 使用新的月份更新当前月份。
- day = c(21, 2, 13) - 使用新的天数更新当前天数。