Lubridate 是你的朋友。准确的说是函数dmy_hms:
我将生成一些与您的示例格式相同的示例数据,以便我的代码可重现。不要太担心它。为了您的目的,您可以直接跳到转换部分。
#------------------------------------------------------------------------------------------
#This code block is entirely for generating reproducible sample data
d <- sample(1:27,10,T)
mon <- toupper(sample(month.abb,10,T))
y <- sample(2000:2017,10,T)
h <- sample(0:23,10,T)
min <- sample(0:59,10,T)
s <- sample(0:59,10,T)
#load package
library(lubridate)
dts <- sprintf('%02d%s%s:%s:%s:%s.000',d,mon,y,h,min,s)
> dts
[1] "01JAN2012:12:6:53.000" "01NOV2010:0:19:47.000" "03SEP2000:9:45:3.000" "25NOV2009:21:39:57.000" "08DEC2015:19:27:36.000"
[6] "23MAR2009:13:39:40.000" "03JUN2010:14:54:50.000" "03APR2002:6:34:45.000" "19NOV2012:5:17:29.000" "02FEB2003:0:3:59.000"
#------------------------------------------------------------------------------------------
所以基本上变量dts 是您要转换的充满日期的列:
#conversion
> dmy_hms(dts)
[1] "2012-01-01 12:06:53 UTC" "2010-11-01 00:19:47 UTC" "2000-09-03 09:45:03 UTC" "2009-11-25 21:39:57 UTC"
[5] "2015-12-08 19:27:36 UTC" "2009-03-23 13:39:40 UTC" "2010-06-03 14:54:50 UTC" "2002-04-03 06:34:45 UTC"
[9] "2012-11-19 05:17:29 UTC" "2003-02-02 00:03:59 UTC"
然后要获得年份,您可以使用year 函数:
> year(dmy_hms(dts))
[1] 2012 2010 2000 2009 2015 2009 2010 2002 2012 2003
因此,假设您想在 data.frame 中执行所有操作,您的代码可能如下所示:
# example dataframe
dframe <- data.frame(variable=c('A','B','C'),dates=sample(dts,3))
这是一个带有一些变量的数据框和带有日期的列。
> dframe
variable dates
1 A 15JAN2000:0:37:6.000
2 B 13DEC2016:8:34:28.000
3 C 18AUG2005:2:27:16.000
所以要转换日期,我们可以简单地做dframe$dates <- year(dmy_hms(dframe$dates))
如果我们再次查看dframe,可以看到转换成功:
> dframe
variable dates
1 A 2000
2 B 2016
3 C 2005