从R的excel中导入处理date和时间

我有来自硬拷贝文件的数据,必须先在excel文件中手动input,以便以后在R中处理。数据包含在不同时间点(例如08:10)针对不同主题(通过ID)的多个读数(Reading) ,08:20等)在不同的date(18.08.2014,2014年8月19日)。 每个阅读系列的参考开始时间(例如,08:00)和参考开始date(例如,18.08.2014)可用。

包含数据的excel文件将如下所示

ID Reading Date Time Ref/Start Time Ref/Start Date 1 12.1 18.08.2014 7:59 8:00 18.08.2014 1 26.34 18.08.2014 8:10 8:00 18.08.2014 1 35.2 18.08.2014 8:20 8:00 18.08.2014 1 30 18.08.2014 8:30 8:00 18.08.2014 1 12 19.08.2014 8:00 8:00 18.08.2014 1 13 19.08.2014 20:00 8:00 18.08.2014 1 12 20.08.2014 8:00 8:00 18.08.2014 

这些数据必须在R中稍后处理。我的目标是生成一个新的列,其中包含每个阅读系列的开始时间点之后的几个小时的每个阅读时间。 所以说得到(y)与(x)其中(x)是以小时为单位的时间。 我现在将这个excel文件导入到R中(以前保存为.csv),但我不知道现在应该如何继续在R中生成新列! 我应该甚至插入数据的另一种方式在Excel中的第一个?

我希望我能成功地澄清我所需要的东西,并且能够find一个人的帮助。

提前谢谢了。

有很多方法可以做到这一点。 这是一个。

假设你有一个名为time_d.csv的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 

对于您的特定数据,date的格式对于这一行很重要: as.POSIXct(strptime(a1$date_read,"%d.%m.%Y %H:%M" ))如果更改date格式,则你也应该在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