r - 在 r 中使用 lubridate 将字符串转换为日期类型
问题描述
我有一列 dateofbirth 包含日期的字符串类型,例如 11-12-89,我想将其转换为日期类型,以便使用 lubridate::year() 来提取年份。我想知道如何将其转换为日期格式,如 11/12/1989 )。顺便说一句,当使用 fwrite() 输出 csv 文件并在 excel 中读取时显示出生日期类似于“1989 年 11 月 12 日”,但在 r 中使用 fread 读取原始文件时出生日期类似于“11- 12-89"。
先感谢您。
解决方案
假设您拥有的日期格式是日期-月-年。
在基础 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)
推荐阅读
- javascript - Javascript:作为参数传递时确定基元的类型
- javascript - nodejs v10.3.0 的 gulp 任务问题:src\node_contextify.cc:629: Assertion `args[1]->IsString()' failed
- php - 在 php 控制器中填充映射数组
- html - 用按钮和输入填充div的宽度
- mysql - 在mysql中显示相同orderNo的下一行总列中上一行的余额列数据
- actions-on-google - 我应该为热泵使用哪些设备类型/特性?
- cumulocity - 删除由片段名称选择的许多托管对象
- docker - Docker,ENOENT:没有这样的文件或目录
- cuda - CUDA 扫描伪代码错误?
- android - 把recyclerview放在recyclerview里面好不好?