将序列号转换为R中的字符表示

时间:2014-02-14 13:03:27

标签: r date

我正在导入一些天气数据,但时间戳分为不同的列。我想加入这些列并从中创建posix对象。

datenum <- c()
for (i in 1:dim(weather)[1]){

date_string <- paste0(weather$Year.UTC[i],'-',weather$Month.UTC[i],'-',weather$Day.UTC[i],'-',weather$Hour.UTC[i]) # different columns of data
# for i = 1, date_string = "2012-12-31-23"

datenum[i] <- as.POSIXct(date_string, format="%Y-%m-%d-%H",tz="GMT", origin = "1960-01-01")
# for i = 1, datenum[1] = 1356994800 (numeric)
}

as.Date(datenum[1], origin = "1960-01-01")
# Gives character = "7285-07-27"

为了直观地确认我做得对,我希望看到“yyyy-mm-dd HH:MM:SS”形式的字符串,这是我尝试用as.Date获得的。转换为序列号并返回字符时,原点是相同的,但日期完全错误。我做错了什么?

1 个答案:

答案 0 :(得分:1)

为什么这么复杂?

weather <- data.frame(Year.UTC=c(2012, 2013), 
                      Month.UTC=c(1,2), 
                      Day.UTC=c(1,2),
                      Hour.UTC=c(22,23))
weather <- within(weather, datetime <- 
              as.POSIXct(paste(Year.UTC, Month.UTC, Day.UTC, Hour.UTC, sep="-"),
                         format="%Y-%m-%d-%H", tz="UTC"))

#  Year.UTC Month.UTC Day.UTC Hour.UTC            datetime
#1     2012         1       1       22 2012-01-01 22:00:00
#2     2013         2       2       23 2013-02-02 23:00:00

如您所见,您根本不需要循环。