2011-12-22 65 views
0

我試圖從減去2次格式化答案。對時差的R格式答案

下面是一個例子:

> timer2$tdif2 <- as.numeric(strptime(as.character(timer2$time3), "%H:%M:%S:%OS") - strptime(as.character(timer2$time2), "%H:%M:%S:%OS")) 
> timer2$tdif1 <- as.numeric(strptime(as.character(timer2$time2), "%H:%M:%S%OS") - strptime(as.character(timer2$time1), "%H:%M:%S%OS")) 
> timer2$tdif2 <- as.numeric(strptime(as.character(timer2$time3), "%H:%M:%S:%OS") - strptime(as.character(timer2$time2), "%H:%M:%S:%OS")) 
> timer2$tdifMax <- as.numeric(strptime(as.character(timer2$time3), "%H:%M:%S.%OS") - strptime(as.character(timer2$time1), "%H:%M:%S.%OS")) 
> head(timer2) 
     time1  time2  time3   tdif1 tdif2 tdifMax 
1 08:00:20.799 08:00:20.799 08:00:20.799 0.0000000000 NA  0 
2 08:00:21.996 08:00:22.071 08:00:23.821 -0.9249999523 NA  2 
3 08:00:29.200 08:00:29.200 08:00:29.591 0.0000000000 NA  0 
4 08:00:31.073 08:00:31.372 08:00:31.384 0.2990000248 NA  0 
5 08:00:31.867 08:00:31.867 08:00:31.971 0.0000000000 NA  0 
6 08:00:37.174 08:00:38.073 08:00:38.153 -0.1010000706 NA  1 

我已經用於tdif1,tdif2和tdif3但他們都不第二部分不同的格式公式給在第二秒和部分答案(爲tdif [2]應該是.075)。有什麼建議麼?

回答

8

您的格式錯誤,您的數據格式爲"%H:%M:%OS"。另外我建議你用數字來做數學運算 - 這會讓你時刻保持秒鐘。

所以,你的例子:

sec <- function(x) as.numeric(strptime(x, "%H:%M:%OS")) 

timer2$tdif1 <- sec(timer2$time2) - sec(timer2$time1) 
timer2$tdif2 <- sec(timer2$time3) - sec(timer2$time2) 
timer2$tdifMax <- sec(timer2$time3) - sec(timer2$time1) 

和輸出:

> head(timer2) 
     time1  time2  time3  tdif1  tdif2 tdifMax 
1 08:00:20.799 08:00:20.799 08:00:20.799 0.00000000 0.00000000 0.0000000 
2 08:00:21.996 08:00:22.071 08:00:23.821 0.07500005 1.75000000 1.8250000 
3 08:00:29.200 08:00:29.200 08:00:29.591 0.00000000 0.39100003 0.3910000 
4 08:00:31.073 08:00:31.372 08:00:31.384 0.29900002 0.01200008 0.3110001 
5 08:00:31.867 08:00:31.867 08:00:31.971 0.00000000 0.10399985 0.1039999 
6 08:00:37.174 08:00:38.073 08:00:38.153 0.89899993 0.08000016 0.9790001 
+0

完美,非常感謝你! – screechOwl 2011-12-22 01:50:26

+0

歡迎來到SO,Simon。很好的「功能性」答案。 – 2011-12-22 02:30:25