%% Resample and Aggregate Data in Timetable
% This example shows how to resample and aggregate data in a timetable. A timetable is a type of table that associates a time with each row. A timetable can store column-oriented data variables that have different data types and sizes, provided that each variable has the same number of rows. With the retime function, you can resample timetable data, or aggregate timetable data into time bins you specify.
%% Import Timetable
% Load a timetable containing weather measurements taken from November 15, 2015, to November 19, 2015. The timetable contains humidity, temperature, and pressure readings taken over this time period.

load outdoors
outdoors(1:5,:)

%
% Determine if the timetable is regular. A regular timetable is one in which the differences between all consecutive row times are the same. outdoors is not a regular timetable.

TF = isregular(outdoors)

%
% Find the differences in the time steps. They vary between half a minute and an hour and a half.

dt = unique(diff(outdoors.Time))

%
%% Resample Timetable with Interpolation
% Adjust the data in the timetable with the retime function. Specify an hourly time vector. Interpolate the timetable data to the new row times.

TT = retime(outdoors,'hourly','spline');
TT(1:5,:)

%
%% Resample Timetable with Nearest Neighbor Values
% Specify an hourly time vector for TT. For each row in TT, copy values from the corresponding row in outdoors whose row time is nearest.

TT = retime(outdoors,'hourly','nearest');
TT(1:5,:)

%
%% Aggregate Timetable Data and Calculate Daily Mean
% The retime function provides aggregation methods, such as mean. Calculate the daily means for the data in outdoors.

TT = retime(outdoors,'daily','mean');
TT

%
%% Adjust Timetable Data to Regular Times
% Calculate the means over six-hour time intervals. Specify a regular time step using the 'regular' input argument and the 'TimeStep' name-value pair argument.

TT = retime(outdoors,'regular','mean','TimeStep',hours(6));
TT(1:5,:)

%
% As an alternative, you can specify a time vector that has the same six-hour time intervals. Specify a format for the time vector to display both date and time when you display the timetable.

tv = datetime(2015,11,15):hours(6):datetime(2015,11,18);
tv.Format = 'dd-MMM-yyyy HH:mm:ss';
TT = retime(outdoors,tv,'mean');
TT(1:5,:)

% Copyright 2012 The MathWorks, Inc.