将因子转换为R中的日期 [英] Converting Factor to Date in R

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

问题描述

我有一个从大量的.csv文件导入的数据集。日期导入作为一个因素,但数据采用以下格式

I have a dataset imported from a large group of .csv file. The date imports as a factor, but the data is in the following format

,    11,   4480, - 4570,NE,  12525,LB, ,    10,      ,  ,    ,    0, 7:26A,26OC11,        
 ,    11,   7090, - 7290,NE,   5250,LB, ,     9,      ,  ,    ,    0, 7:28A,26OC11,        
 ,    11,   5050, - 5065,NE,     50,LB, ,     7,      ,  ,    ,    0, 7:31A,26OC11,        
 ,    12,   5440, - 5530,NE,  13225,LB, ,     6,      ,  ,    ,    0, 8:10A,26OC11,        
 ,    12,   1020, - 1220,NE,  12020,LB, ,    14,      ,  ,    ,    0, 8:12A,26OC11,        
 ,    12,     50, -   25,NE,  12040,LB, ,    15,      ,  ,    ,    0, 8:13A,26OC11,      
4

例如2011年10月26日。如何将这些因素转换为日期和时间。我需要能够使用时间来生成记录之间的时间间隔。

For example would be 26 Oct 2011. How would I convert these factors to a date and the time to a time. I need to be able to use the time to generate a time interval between records.

推荐答案

你确定只有两个字母这个月?这没有任何意义!你怎么在6月和7月之间告诉?如果你可以得到三个字母,你可以这样做一些简单的事情。

Are you sure there are only two letters for the month? That doesn't make any sense!, how do you tell between JUNE and JULY?. If you can get three letters you could do something simple like this.

as.Date(as.character(mydata$mydate), format = '%d%b%y')

您还可以使用levels()[]而不是as.character(),但现在应该更简单

You could also use levels()[] instead of as.character(), but this should be simpler for now

现在,如果你也想要时间。你可以用这个命令把它放在一起。

Now if you also want the time. You can put it all together with this command

as.POSIXct(strptime(paste(as.character(mydata$mydate), paste(as.character(mydata$mytime), "M", sep = "")), "%d%b%y %I:%M%p"))

您必须特别注意格式。你可以看到一个%I,%d等等的列表,这意味着...这里 http://stat.ethz.ch/R-manual/R-devel/library/base/html/strptime.html

You have to be specially careful with the format. You can see a list of what %I, %d and so, means... here http://stat.ethz.ch/R-manual/R-devel/library/base/html/strptime.html

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

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