2013-06-25 23 views
3

我有MATLAB的以往的經驗,但很新,R.,我有基本的問題是這樣的 - 我有一個具有10列的數據等效datenum的編程

。前6列對應年,月,日,小時分和秒。

E.g data_example = 
2013 6 15 11 15 0 ... 
2013 6 15 11 20 0 ... 
2013 6 15 11 25 0 ... 

在MATLAB與日期處理,因爲我很容易地計算數字,使用datenum(data_example(:,1:6))

但R中的是去獲得6列的類似數字表示的最佳方式。

+0

你可以發佈你的數據樣本,並告訴我們期望的輸出應該是什麼樣子? –

回答

0

使用Lubridate包中的parse_date_time函數。在documentation

編輯 @joran

x <- paste0(data_example[,1:6]) 
x <- parse_date_time(x,"%y%m%d %H%M") 

更多信息告訴我要測試它,它沒有工作,所以我做了一些修改:

data_example = data.frame(t(c(13,2,9,14,30))) 
x <- paste0(data_example[,1:3],collapse="-") 
y <- paste0(data_example[,4:5],collapse=":") 
xy<- paste(x,y) 
xy <- parse_date_time(xy,"%y%m%d %H%M") 
xy 
# "2013-02-09 14:30:00 UTC" 

我不不知道是否有更乾淨的方法去做

+0

我想你用'data_example(:,1:6)'混合了一些matlab語法。 – joran

+0

你是對的,對不起。我將編輯 – eyanquenb

+0

這是至少R代碼,但我不認爲它會做你認爲它會。試用一個小樣本數據框。 – joran

0

返回值的單位有點不同在R中的t比在Matlab中(見代碼註釋)。另外,由於數據框中有其他列,因此首先需要對數據框進行子集化,以僅包含相關的(6)日期列,然後將它們作爲新列添加回數據框。

test <- data.frame("year"=c(2013, 2013, 2013, 2001, 1970) 
        , "month"=c(6,6, 6, 4, 1) 
        , "day"=c(15,15, 15, 19, 1) 
        , "hour"=c(11,11, 11, 11, 0) 
        , "min"=c(15,20, 25, 30, 0) 
        , "second"=c(0,0, 0 ,0, 0)) 
# pad to the right # of digits 
dates00 <- apply(test, c(1,2), sprintf, fmt="%02s") 
# combine the date components in each row into a single string 
dates0 <- apply(dates00, 1, paste, collapse=" ") 
#format to a date object 
dates <- as.POSIXct(dates0, format="%Y %m %d %H %M %S") 
# numbers are seconds since "1970-01-01 00:00:00 UTC"; according 
# to the help file for daynum, Matlab returns the number (from 
# daynum) as fractional days since "January 0, 0000" 
as.numeric(dates) 
2

下面是一些替代方案。他們都利用ISOdatetime

1)假設DF是您的數據幀嘗試ISOdatetime這樣的:

DF$datetime <- ISOdatetime(DF[[1]], DF[[2]], DF[[3]], DF[[4]], DF[[5]], DF[[6]]) 

2)或像這樣:

DF$datetime <- do.call(ISOdatetime, setNames(as.list(DF[1:6]), NULL)) 

3A )如果這是適合動物園的時間序列(不同時間和所有數字),那麼我們可以使用read.zoo在動物園包ISOdatetime這樣在一起:

library(zoo) 
z <- read.zoo(DF, index = 1:6, FUN = ISOdatetime) 

3b)的或使用read.zoo從文件或字符串來讀取(後者在這裏示出):

# sample input lines 
Lines <- "2013 6 15 11 15 0 1 
2013 6 15 11 20 0 2 
2013 6 15 11 25 0 3 
" 

library(zoo) 
z <- read.zoo(text = Lines, index = 1:6, FUN = ISOdatetime) 

這給這個動物園系列:

> z 
2013-06-15 11:15:00 2013-06-15 11:20:00 2013-06-15 11:25:00 
        1     2     3