将"2008年1月"转换为迄今为止的变量 [英] Convert "Jan.2008" to date variable

查看:48
本文介绍了将"2008年1月"转换为迄今为止的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将以下字符变量转换为日期?

How would I convert the following character variables to dates?

strDates <- c("Jan.2008", "Feb.2008")
str(strDates)
chr [1:2] "Jan.2008" "Feb.2008"

dates <- as.Date(strDates, "%b %Y")
str(dates)
Date[1:2], format: NA NA

任何帮助将不胜感激

推荐答案

日期也需要一个day元素,因此您可以使用 paste :

A Date requires a day element as well, so you can add that to the input string with paste:

full.dates <- paste("01", strDates, sep = ".")

正确指定模板,包括分隔符:

Specify the template correctly, including separator tokens:

as.Date(full.dates, "%d.%b.%Y")
[1] "2008-01-01" "2008-02-01"

这篇关于将"2008年1月"转换为迄今为止的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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