首页 > 解决方案 > 在 r 中使用 lubridate 将字符串转换为日期类型

问题描述

我有一列 dateofbirth 包含日期的字符串类型,例如 11-12-89,我想将其转换为日期类型,以便使用 lubridate::year() 来提取年份。我想知道如何将其转换为日期格式,如 11/12/1989 )。顺便说一句,当使用 fwrite() 输出 csv 文件并在 excel 中读取时显示出生日期类似于“1989 年 11 月 12 日”,但在 r 中使用 fread 读取原始文件时出生日期类似于“11- 12-89"。

先感谢您。

标签: rlubridate

解决方案


假设您拥有的日期格式是日期-月-年。

在基础 R 中,您可以使用:

#Convert to date
df$dateofbirth <- as.Date(df$dateofbirth, '%d-%m-%y')
#Get the year
df$year <- as.integer(format(df$dateofbirth, "%Y"))

或与lubridate

library(lubridate)
df$dateofbirth <- dmy(df$dateofbirth)
df$year <- year(df$dateofbirth)

推荐阅读