2014-08-27 38 views
1

我有来自硬拷贝纸的数据,必须先在Excel文件中手动输入以后在R中处理。 数据包含针对不同主题的多个读数变量(读数) (身份证)在不同日期(2014年8月18日,2014年8月19日)的不同时间点(如08:10,08:20等)。每个阅读系列的参考开始时间(例如08:00)和参考开始日期(例如,18.08.2014)可用。从Excel中导入的处理日期和时间R

包含数据看起来就像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 

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

我希望我能够成功地澄清我需要的东西,并且我可以从某人那里找到帮助之手。

非常感谢提前。

回答

2

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

假设你有一个名为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 
+0

很多很多很多的感谢。它没有工作:)我真的很感激你的帮助下looooot ... – 2014-08-27 11:48:44

+0

此评论额外感谢你为清你的答案的演示文稿...竖起大拇指 – 2014-08-27 11:56:16

+1

没有probs。感谢您给出答案。欢迎再来 – 2014-08-27 12:09:57