2016-03-22 107 views
1

我有一个数据集(称为标数据)看起来像这样的R中总结:时间标准

Date_Time   Cost 
---------   ----- 
01/02/2015 01:52 PM 6  
01/02/2015 02:22 PM 2  
01/03/2015 02:42 PM 50 
01/04/2015 03:01 PM 25 

和不同的数据集(客户数据),看起来像这样:

Purchase_time   Amount 
-------------   --------- 
01/02/2015 01:57 PM   5 
01/02/2015 02:46 PM   12 
01/02/2015 03:13 PM   2 
01/02/2015 03:30 PM   8 

我想从日期时间列中的客户数据中总结“金额”列,用于不同时间窗口的印花数据,最终结果如下所示:

Date_Time   Cost  Amount_15min Amount_30min 
---------   ----- -------------- ------------- 
01/02/2015 01:52 PM 6   5    5 
01/02/2015 02:22 PM 2   0   12 
01/03/2015 02:42 PM 50   12   12 
01/04/2015 03:01 PM 25   8   8 

理想情况下,我想要创建15分钟间隔的列,需要360分钟(或更多)

如何在R中执行此操作?

谢谢!

回答

0

我想你会直接找到大部分代码。我们需要将日期转换为POSIX对象来对它们执行数学运算。 POSIX对象以整数形式存储,表示自01/01/1970以来经过的秒数,因此在对它们执行数学运算时,我们将转换为数字,然后从它们中增加/减去秒。

### Build test data frame 
### times is a character vector and cost is a numeric vector 
times <- c(
"01/02/2015 01:52 PM", 
"01/02/2015 01:57 PM", 
"01/02/2015 01:58 PM", 
"01/02/2015 02:52 PM", 
"01/02/2015 02:55 PM") 

cost <- c(8, 2, 50, 26, 7) 

df <- data.frame(times = times, cost = cost, stringsAsFactors = FALSE) 


#### convert times to POSIX dates 
df$times <- strptime(df$times, format = "%m/%d/%Y %I:%M %p") 

### polling frequency in minutes 
pollinglength <- 15 

### create empty vector to hold sums 
amount <- rep(NA, nrow(df)) 

for(i in 1:nrow(df)){ 

    ### POSIX support comparison operators well 
    upperWindow <- df$times <= df$times[i] 

    ### POSIX does not support addition/subtraction well, so we will convert to numeric first 
    lowerWindow <- as.numeric(df$times) > (as.numeric(df$times[i]) - pollinglength * 60) 

    amount[i] <- sum(df$cost[ upperWindow & lowerWindow ]) 
} 

### Add back to data frame 
df <- cbind(df, amount) 
+0

嘿克里斯,谢谢你!但我想要做的是在第一个数据框(标记数据)的日期之间汇总来自第二个数据框(客户数据)的数据,成本实际上只是一个任意列,我将其包含在内以表明我需要它在最后的数据框中。 – Julia

+0

没问题。如果它解决了您的问题,请将其标记为答案。否则,让我知道你是否需要帮助。 –

+0

如果问题在于它们处于单独的数据框中,请事先运行 –