【问题标题】:convert string to date type with lubridate in r在 r 中使用 lubridate 将字符串转换为日期类型
【发布时间】:2020-03-10 04:22:27
【问题描述】:

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

提前谢谢你。

【问题讨论】:

  • 一般建议:添加相关代码 sn-ps 可以提高人们理解和回答您的问题的机会,并且这些答案更加详细和有用。
  • 会的,谢谢

标签: r lubridate


【解决方案1】:

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

在基础 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)

【讨论】:

    猜你喜欢
    • 2019-04-10
    • 2012-12-09
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    • 2013-07-05
    相关资源
    最近更新 更多