有很多方法可以做到这一点。这是一个。
假设你有一个名为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