我在R工作,我需要从格式的列更改
9/27/2011 3:33:00 PM
Run Code Online (Sandbox Code Playgroud)
到一个值格式.在Excel中,我可以使用该功能,value()但我不知道如何在R中执行此操作.
我的数据如下:
9/27/2011 15:33 a 1 5 9
9/27/2011 15:33 v 2 6 2
9/27/2011 15:34 c 3 7 1
Run Code Online (Sandbox Code Playgroud)
And*_*rie 25
要将字符串转换为R日期格式,请使用as.POSIXct- 然后您可以使用as.numeric以下方法将其强制转换为数值:
> x <- as.POSIXct("9/27/2011 3:33:00 PM", format="%m/%d/%Y %H:%M:%S %p")
> x
[1] "2011-09-27 03:33:00 BST"
> as.numeric(x)
[1] 1317090780
Run Code Online (Sandbox Code Playgroud)
您获得的值表示自任意日期以来的秒数,通常是1970年1月1日.请注意,这与Excel不同,其中日期存储为自任意日期以来的天数(如果我的记忆能很好地用于我,则为1/1/1900 - 我不再使用Excel了.)
有关更多信息,请参阅 ?DateTimeClasses
这对我很有用:
> test=as.POSIXlt("09/13/2006", format="%m/%d/%Y")
> test
[1] "2006-09-13"
> 1900+test$year
[1] 2006
> test$yday
[1] 255
> test$yday/365
[1] 0.6986301
> 1900+test$year+test$yday/366
[1] 2006.697
Run Code Online (Sandbox Code Playgroud)
如果您需要像 Excel 中那样的天数,您可以使用类似的方法。