简体   繁体   English

使用 r 中的 lubridate 将字符串转换为日期类型

[英]convert string to date type with lubridate in r

I have a column dateofbirth contain string type of date such as 11-12-89, I want to convert it to date type in order to use lubridate::year() to extract the year.我有一列 dateofbirth 包含日期的字符串类型,例如 11-12-89,我想将其转换为日期类型以便使用 lubridate::year() 来提取年份。 I am wondering how to convert this to date format like 11/12/1989 ).我想知道如何将其转换为日期格式,如 11/12/1989 )。 By the way, when use fwrite() to output the csv file and read in excel show the dateofbirth is something like "11/12/1989", but in r when use fread to read the original file the dateofbirth is like "11-12-89".顺便说一句,当使用 fwrite() 输出 csv 文件并在 excel 中读取时显示出生日期类似于“11/12/1989”,但在 r 中使用 fread 读取原始文件时,出生日期类似于“11- 12-89"。

Thank you in advance.先感谢您。

Assuming the date format that you have is date-month-year.假设您拥有的日期格式是日期-月-年。

In base R, you can use :在基础 R 中,您可以使用:

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

OR with lubridate或用lubridate

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM