如何在R中将字符转换为日期格式? [英] How to convert character to Date format in R?

查看:628
本文介绍了如何在R中将字符转换为日期格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将以下字符转换为日期格式?

How to convert the below in character to Date format?

YYYY.MM

我遇到了第10个月小数点后为零的问题。

I am facing an issue dealing with zeroes after decimal points for month 10. Say

2012.10 

出现在我的输入源数据中

appears in my input source data as

2012.1

,缺少十进制的零。

推荐答案

因为您只有 month ,则需要在 day 分配一些值,然后再转换为日期。在下面的示例中,日期被任意选择为 15

Since you have only year and month, you need to assign some value for day before you convert to date. In the example below, the day has arbitrarily been chosen as 15.

如果输入字符

dates = c("2012.10", "2012.01")

lubridate::ymd(paste0(year_month = dates, day = "15"))
#[1] "2012-10-15" "2012-01-15"

如果输入为数字

dates = c(2012.10, 2012.01)

do.call(c, lapply(strsplit(as.character(dates), "\\."), function(d){
    if(nchar(d[2]) == 1){
        d[2] = paste0(d[2],"0")
    }
    lubridate::ymd(paste0(year = d[1], month = d[2], day = "15"))
}))
#[1] "2012-10-15" "2012-01-15"

这篇关于如何在R中将字符转换为日期格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆