有很多方法可以做到這一點。這是一個。
假設你有一個名爲CSV文件中的數據time_d.csv
你可以這樣做:
time_d.csv看起來是這樣的:
ID Reading Date Time Ref_time Ref_date
1 12.1 18.08.2014 07:59 08:00 18.08.2014
1 26.34 18.08.2014 08:10 08:00 18.08.2014
1 35.2 18.08.2014 08:20 08:00 18.08.2014
1 30 18.08.2014 08:30 08:00 18.08.2014
1 12 19.08.2014 08:00 08:00 18.08.2014
1 13 19.08.2014 20:00 08:00 18.08.2014
1 12 20.08.2014 08:00 08:00 18.08.2014
你可以看到,我已經略有改變列標題。然後,以這種格式的.csv,你可以這樣做:
a1=read.csv("time_d.csv") #reads data into R data frame
a1$date_read=paste(a1$Date, a1$Time, sep=" ") #adds a new col to data frame
#by merging two existing cols
a1$date_ref=paste(a1$Ref_date, a1$Ref_time, sep=" ") #adds new col
a1=subset(a1,select=-c(Date,Time)) #removes the no longer needed cols
a1=subset(a1,select=-c(Ref_date,Ref_time)) #removes the no longer needed cols
a1$date_read=as.POSIXct(strptime(a1$date_read,"%d.%m.%Y %H:%M")) #convert
#to date/time objects
a1$date_ref=as.POSIXct(strptime(a1$date_ref,"%d.%m.%Y %H:%M"))
a1$Duration=difftime(a1$date_read,a1$date_ref, units="hours") #adds new col
#calculating the time difference in hours
您的特定數據日期的格式是該行重要的: as.POSIXct(strptime(a1$date_read,"%d.%m.%Y %H:%M"))
如果更改日期的格式,那麼你應該改變這行代碼也在R中。
最終的結果看起來是這樣的:
ID Reading date_read date_ref Duration
1 1 12.10 2014-08-18 07:59:00 2014-08-18 08:00:00 -0.01666667 hours
2 1 26.34 2014-08-18 08:10:00 2014-08-18 08:00:00 0.16666667 hours
3 1 35.20 2014-08-18 08:20:00 2014-08-18 08:00:00 0.33333333 hours
4 1 30.00 2014-08-18 08:30:00 2014-08-18 08:00:00 0.50000000 hours
5 1 12.00 2014-08-19 08:00:00 2014-08-18 08:00:00 24.00000000 hours
6 1 13.00 2014-08-19 20:00:00 2014-08-18 08:00:00 36.00000000 hours
7 1 12.00 2014-08-20 08:00:00 2014-08-18 08:00:00 48.00000000 hours
很多很多很多的感謝。它沒有工作:)我真的很感激你的幫助下looooot ... – 2014-08-27 11:48:44
此評論額外感謝你爲清你的答案的演示文稿...豎起大拇指 – 2014-08-27 11:56:16
沒有probs。感謝您給出答案。歡迎再來 – 2014-08-27 12:09:57