2013-02-11 52 views
1

使用矩陣I具有如下面的矩陣,以計算時間(第一行是:):如何作爲R

method  start   i2   i3   i4   i5   i7   
1 "m1" "17:19:02" "17:19:10" "17:19:18" "17:19:26" "17:19:36" "17:19:47" 

所以每一行中的我有method name然後start time然後在end time每個i(x)區間。我需要計算每個i(x)這是(start time - i(x) time)的時間量。我認爲我需要將格式改爲時間,然後進行減號,但我不知道如何去做。

回答

3
#some data 
df <- read.table(text='method  start   i2   i3   i4   i5   i7   
1 "m1" "17:19:02" "17:19:10" "17:19:18" "17:19:26" "17:19:36" "17:19:47" 
2 "m2" "17:19:05" "17:19:10" "17:19:18" "17:19:26" "17:19:36" "17:19:47"',stringsAsFactors=FALSE) 

m <- as.matrix(df) 


#transform matrix to data.frame 
df <- as.data.frame(m,stringsAsFactors=FALSE) 

#melt to long format 
library(reshape2) 
df <- melt(df,id.vars="method") 
#transform to date-time 
df$value <- as.POSIXct(df$value,"%H:%M:%S",tz="GMT") 

#calculate time differences 
library(plyr) 
ddply(df,.(method),transform,timediff = value-value[variable=="start"]) 

    method variable    value timediff 
1  m1 start 2013-02-11 17:19:02 0 secs 
2  m1  i2 2013-02-11 17:19:10 8 secs 
3  m1  i3 2013-02-11 17:19:18 16 secs 
4  m1  i4 2013-02-11 17:19:26 24 secs 
5  m1  i5 2013-02-11 17:19:36 34 secs 
6  m1  i7 2013-02-11 17:19:47 45 secs 
7  m2 start 2013-02-11 17:19:05 0 secs 
8  m2  i2 2013-02-11 17:19:10 5 secs 
9  m2  i3 2013-02-11 17:19:18 13 secs 
10  m2  i4 2013-02-11 17:19:26 21 secs 
11  m2  i5 2013-02-11 17:19:36 31 secs 
12  m2  i7 2013-02-11 17:19:47 42 secs 
+0

你是對的,但我不想做任何假設。 (這裏的時間可能只會增加嗎?姓氏是否始終遵循問題中的模式?) – Roland 2013-02-11 12:38:14

+0

非常感謝@Roland – hora 2013-02-13 16:22:41