我必须在数据框中修复一个日期。日期为“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)
}
这是 coursera r 课程之一的家庭作业。