简体   繁体   English

分割时间序列并将不同的函数应用于R中的不同列

[英]Spliiting a time series and applying different functions to different columns in R

Suppose this is the dataframe (dt): 假设这是数据帧(dt):

        datetime        price1    price2
2011-01-04 22:00:20       1         7
2011-01-04 22:01:37       2         8 
2011-01-04 22:01:57       3         9
2011-01-04 22:03:03       4        10
2011-01-04 22:03:32       5        11
2011-01-04 22:03:45       6        12

I want to split the data by datetime (1 min intervals) and find: 我想按日期时间(1分钟间隔)分割数据并找到:

For price1: the last observation minus the first. 对于price1:最后的观察值减去第一个观察值。

For price2: sum of all prices. 对于price2:所有价格的总和。

        time           difference    sum
2011-01-04 22:00:00      1-1=0           7
2011-01-04 22:01:00      3-2=1          17
2011-01-04 22:03:00      6-4=2          33


dt$time <- cut(dt$datetime, "1 min")
dt1min<-ddply(dt,.(time), function(x))

How should I define the function(x)? 我应该如何定义函数(x)? Thanks. 谢谢。

Here is my solution using the data.table package: 这是我使用data.table包的解决方案:

library(data.table)

dt <- data.table(datetime= c("2011-01-04 22:00:20",
                             "2011-01-04 22:01:37",
                             "2011-01-04 22:01:57",
                             "2011-01-04 22:03:03",
                             "2011-01-04 22:03:32",
                             "2011-01-04 22:03:45"),
                 price1 = c(1,2,3,4,5,6),
                 price2 = c(7,8,9,10,11,12))

dt[, datetime:= as.POSIXct(datetime)] # convert character to timestamp
dt[, time:= format(datetime, "%Y-%m-%d %H:%M")] # create time column

# now split apply,combine
dt[, list(difference = price1[datetime==max(datetime)] - price1[datetime==min(datetime)],
          sum        = sum(price2)),
   by = time]

the output is: 输出为:

              time difference sum
1: 2011-01-04 22:00          0   7
2: 2011-01-04 22:01          1  17
3: 2011-01-04 22:03          2  33

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM