将字符转换为R中的日期 [英] Convert character to Date in R

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

问题描述

我对R还是比较陌生,但这是我第一次必须处理日期转换.我从CSV中读取了数据(使用read.table()),但我将数据缩短以突出显示我的问题.当读入R时,日期"字段为字符.

I am relatively new to R, but this is the first time I have had to deal with date conversions. I read in my data from a CSV (using read.table()), but I shorted the data to highlight my issue. When read into R, the Date field is character.

简而言之,除了少数情况,我的大多数约会都得到了正确的强制.下面的示例有望向您显示正在发生的事情.

Simply, most of my dates get coerced correctly, except for a few instances. The example below will hopefully show you what is going on.

# my attempt to coerce the date -- uses the stringr package
prods.all$Date2 <- as.Date(str_sub(prods.all$Date, 1, 
                str_locate(prods.all$Date, " ")[1]-1), 
                "%m/%d/%Y")

# grab two rows to highlight my issue
temp <- prods.all[c(1925:1926), c(1,8)]

> temp
                   Date      Date2
1925  10/9/2009 0:00:00 2009-10-09
1926 10/15/2009 0:00:00 0200-10-15

如您所见,某些日期的年份不正确.当日期为两位数时,似乎会出现这种模式.

As you can see, the year of some of the dates is inaccurate. The pattern seems to occur when the day is double digit.

我浏览了几本书,并尝试了一种更好的Google搜索方法,但是似乎所有内容都表明我的数据在输入时格式不正确.

I have looked through a couple of books and tried to Google a better way, but everything seems to suggest that my data are not formatted correctly on input.

鉴于R的功能强大,我认为有一种非常简单的方法可以将我的列强制为有效日期,而我却忽略了一个非常明显的解决方案.

Given how powerful R is, I figure that there is a very easy way to force my column to be valid dates and that I am overlooking a very obvious solution.

我们将不胜感激.

推荐答案

您可能使事情复杂化了,请问有什么理由需要Stringer软件包吗?

You may be overcomplicating things, is there any reason you need the stringr package?

 df <- data.frame(Date = c("10/9/2009 0:00:00", "10/15/2009 0:00:00"))
 as.Date(df$Date, "%m/%d/%Y %H:%M:%S")

[1]"2009-10-09""2009-10-15"

[1] "2009-10-09" "2009-10-15"

更一般而言,如果您还需要时间部分,请使用strptime:

More generally and if you need the time component as well, use strptime:

strptime(df$Date, "%m/%d/%Y %H:%M:%S")

我在猜测从您提供的部分结果来看您的实际数据可能会是什么.

I'm guessing at what your actual data might look at from the partial results you give.

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

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