根据我们使用 R 的目的,我们可能需要处理包含日期和时间的数据。
R 为我们提供了各种处理日期和时间的函数。
获取 R 中的当前系统日期和时间
在 R 中,我们分别使用 Sys.Date()
和 Sys.time()
来获取基于本地系统的当前日期和时间。例如:
# get current system date
Sys.Date()
# get current system time
Sys.time()
输出
[1] "2022-07-11" [1] "2022-07-11 04:16:52 UTC"
在上面的示例中,我们使用了不同的函数来获取基于本地系统的当前日期和时间。
这里,
Sys.date()
- 返回当前日期,即 **2022-07-11**Sys.time()
- 返回当前日期、时间和时区,即 **2022-07-11 04:16:52 UTC**
使用 R lubridate 包
R 中的 lubridate
包可以更有效地提取和操作日期值的某些部分。
该包下有多种函数可用于处理日期。
但首先,为了访问 lubridate
包,我们首先需要导入该包,方法如下:
# access lubridate package
library(lubridate)
在这里,我们已成功导入 lubridate 包。
1. 使用 R lubridate 包获取当前日期
# access lubridate package
library(lubridate)
# get current date with time and timezone
now()
# Output: "2022-07-11 04: 34: 23 UTC"
在这里,我们使用了 lubridate
包提供的 now()
函数来获取带时间和时区的当前日期。
2. 在 R 中从多个日期值提取年份、月份和日期
在 R 中,我们使用 lubridate
包提供的 year()
、month()
和 mday()
函数分别从多个日期值中提取年份、月份和日期。例如:
# import lubridate package
library(lubridate)
dates <- c("2022-07-11", "2012-04-19", "2017-03-08")
# extract years from dates
year(dates)
# extract months from dates
month(dates)
# extract days from 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 包允许我们一次性操作多个日期值。例如:
# import lubridate package
library(lubridate)
dates <- c("2022-07-11", "2012-04-19", "2017-03-08")
# increase each year by one year
print(dates + years(1))
# increase each month by one month
print(dates + months(1))
# update days
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()
函数一次性更新多个日期值。例如:
# import lubridate package
library(lubridate)
dates <- c("2022-07-11", "2012-04-19", "2017-03-08")
# update all date values using 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) - 使用新日期更新当前日期。