R代码创建可重用函数以计算年度数据的日期差异

时间:2017-08-15 23:31:03

标签: r

我有以下2个数据集 VechicleParking_InTime

Vehicle_Id  12/31/15        12/30/15        12/29/15        12/27/15 
    2268    12/31/15 10:26  12/30/2015  14:00:00    12/29/15 11:00  NA
    2269    12/31/15 11:00  12/30/15 10:00  12/29/15 10:00  NA
    2270    12/31/15 0:00   12/30/15 7:00   12/29/15 7:00   NA
    2271    12/31/15 11:00  12/30/15 1:00   12/29/15 8:00   NA
    2272    12/31/15 10:00  12/30/15 4:00   12/29/15 9:00   12/27/15 1:00
    2273    NA  12/30/15 7:00   12/29/15 6:00   12/27/15 9:00
    2274    12/31/2015  15:00:00    12/30/15 10:00  12/29/15 5:00   12/27/15 7:00

VehicleParking_OutTime

 Vehicle_Id 12/31/15    12/30/15    12/29/15    12/27/15 
2268    12/31/15 11:26  NA  12/29/2015  13:00:00    NA
2269    12/31/2015  13:00:00    12/30/2015  15:00:00    12/29/15 0:00   NA
2270    12/31/15 9:00   12/30/2015  17:00:00    12/29/2015  17:00:00    NA
2271    12/31/2015  23:00:00    12/30/2015  13:00:00    12/29/2015 18:00:00     NA
2272    12/31/15 10:30  12/30/2015  14:00:00    12/29/2015  19:00:00    12/27/2015  13:00:00 

2273    NA  12/30/2015  17:00:00    12/29/2015  16:00:00    12/27/2015 19:00:00 
2274    12/31/2015  17:00:00    NA  12/29/2015 15:00:00     12/27/2015  17:00:00 

以下是我的挑战 1-列数为365,每列名称为日期,因此我需要一个以列为索引的函数来计算时差 2- intime和outtime都在不同的文件中

我创建了一个功能,该功能成功地用于计算日期差异,但两者都在同一个具有不同列名的文件中

#Using Chron library
    Diff_Minutes <- function(In_Time,Out_Time){
      if(is.na(In_Time) == TRUE){
        return(NA)
      }else{
        return((as.numeric(chron(dates=str_split_fixed(Out_Time," ",2)[,1],times=str_split_fixed(Out_Time," ",2)[,2],format=c('d-m-y','h:m:s'))) - as.numeric(chron(dates=str_split_fixed(In_Time," ",2)[,1],times=str_split_fixed(In_Time," ",2)[,2],format=c('d-m-y','h:m:s'))))*1440)
      }
    }

0 个答案:

没有答案