我必须在数据框中确定日期。日期为“ 16/12/2006”,时间为“ 17:24:00”。我想用合并的日期和时间构造一个posixlt。我尝试过:
fixTime2<-function(date,time) { # replaces the date in time with the parameter date.
fixed<-time
fixed$mon<-as.numeric(format(date,"%m"))
fixed$mday<-as.numeric(format(date,"%d"))
fixed$year<-as.numeric(format(date,"%Y"))-1900
return(fixed)
}
testFixTime2<-function() {
date<-as.Date("16/12/2006", format = "%d/%m/%Y")
str(date)
time<-strptime("17:24:00","%H:%M:%S")
str(time)
fixed<-fixTime2(date,time)
str(fixed)
return(fixed)
}
运行程序时,我得到:
> source("1.R")
> f<-testFixTime2()
Date[1:1], format: "2006-12-16"
POSIXlt[1:1], format: "2018-07-17 17:24:00"
POSIXlt[1:1], format: "2007-01-16 17:24:00"
年份偏离一年,而日期和月份不正确。
我尝试了$ month和$ day,但它们似乎也不起作用。
有没有更简单的方法来构造posixlt?
谢谢
我最后得到了:
require(RUnit)
fixTime<-function(date,time) { # replaces the date in time with the paramer date.
as.POSIXlt(sprintf("%s %s",date,time),format="%d/%m/%Y %H:%M:%S")
}
fixTime2<-function(month,day,year,hours,minutes,seconds) {
print("in function fixTime")
print(year)
date<-paste0(c(day,month,year),collapse="/")
time<-paste0(c(hours,minutes,seconds),collapse=":")
fixed<-fixTime(date,time)
}
test.fixTime<-function() {
month<-"12"
day<-"16"
year<-"2006"
hours<-"17"
minutes<-"24"
seconds<-"00"
print(year)
fixTime2(month,day,year,hours,minutes,seconds)
#fixed<-fixTime(date,time)
checkEquals(as.numeric(month),fixed$mon+1)
checkEquals(as.numeric(day),fixed$mday)
checkEquals(as.numeric(year),fixed$year+1900)
checkEquals(as.numeric(hours),fixed$hour)
checkEquals(as.numeric(minutes),fixed$min)
checkEquals(as.numeric(seconds),fixed$sec)
}
这是其中一门课程的作业。
答案 0 :(得分:0)
如果您有单独的字符串,那么
as.POSIXlt(paste(date, time), format="%d/%m/%Y %H:%M:%S")
应该工作。示例:
as.POSIXlt(paste("16/12/2006", "17:24:00"), format="%d/%m/%Y %H:%M:%S")
# [1] "2006-12-16 17:24:00"
第二点,$month
和$day
不是可用属性。您可以看到类似以下内容的可用属性:
dput(as.POSIXlt(Sys.time()))
# structure(list(sec = 48.7993450164795, min = 17L, hour = 0L,
# mday = 18L, mon = 6L, year = 118L, wday = 3L, yday = 198L,
# isdst = 1L, zone = "PDT", gmtoff = -25200L), .Names = c("sec",
# "min", "hour", "mday", "mon", "year", "wday", "yday", "isdst",
# "zone", "gmtoff"), class = c("POSIXlt", "POSIXt"), tzone = c("",
# "PST", "PDT"))
表明您真正需要的是$mon
和$mday
。