簡體   English   中英

如何在R中的posixlt中設置日,月和年?

[英]how to set the day, month and year in a posixlt in r?

我必須在數據框中確定日期。 日期為“ 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)
}

這是一門課程的家庭作業。

如果您有單獨的字符串,那么

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM