How to separate and order timetable data by year

6 views (last 30 days)
data = readtable('USA_SITE_004_final.txt'); %import text file and present as table
data_nan = standardizeMissing(data, -999); %return '-999' values as 'NaN'
hourly_temp_rain_sm = data_nan(:, [1 5 11 26]); %extract key variables
TT = table2timetable(hourly_temp_rain_sm); %form timetable
daily_temp_rain_sm = retime(TT, 'daily', 'mean'); %retime data to obtain daily averages
daily_sm = daily_temp_rain_sm(:,3);
Hi, i have created a timetable and retimed soil moisture data here to obtain daily averages for a period of several years. I now want to be able to obtain a metric for each year and to do this i will need to separate the data into years, keeping the daily averages each year. I hope that makes sense and thank you in advance for any help.

Answers (1)

Adam Danz
Adam Danz on 15 Nov 2021
Edited: Adam Danz on 15 Nov 2021
> I now want to be able to obtain a metric for each year and to do this i will need to separate the data into years, keeping the daily averages each year.
You can use retime with yearly intervals. By storing this in a different variable, you can also keep the daily values.
dt = datetime(1999,1,1) + days(0:1:2000)';
rainfall = rand(numel(dt),1);
TT = timetable(dt, rainfall) % Daily rainfall
TT = 2001×1 timetable
dt rainfall ___________ ________ 01-Jan-1999 0.09073 02-Jan-1999 0.82922 03-Jan-1999 0.68411 04-Jan-1999 0.15243 05-Jan-1999 0.47396 06-Jan-1999 0.084376 07-Jan-1999 0.50433 08-Jan-1999 0.65501 09-Jan-1999 0.47188 10-Jan-1999 0.29966 11-Jan-1999 0.90719 12-Jan-1999 0.51547 13-Jan-1999 0.47611 14-Jan-1999 0.6801 15-Jan-1999 0.015343 16-Jan-1999 0.56246
yearlyTT = retime(TT,'yearly','mean') % yearly avg
yearlyTT = 6×1 timetable
dt rainfall ___________ ________ 01-Jan-1999 0.52045 01-Jan-2000 0.51869 01-Jan-2001 0.49597 01-Jan-2002 0.50299 01-Jan-2003 0.50966 01-Jan-2004 0.47196
Note that the aggregate method can be a function handle if your metric is not a built-in option. See doc retime for more info.
  6 Comments
Joe Wheeler
Joe Wheeler on 16 Nov 2021
Edited: Adam Danz on 17 Nov 2021
Unfortunately i got this error:
Unable to use a value of type datetime as an index.
Error in Research_Project>@(yr)daily_sm(year(daily_sm.DT)==yr,:) (line 31)
daily_smbyYearFcn = @(yr)daily_sm(year(daily_sm.DT)==yr,:);
Error in Research_Project (line 33)
A = daily_smbyYearFcn(2001);
Adam Danz
Adam Danz on 16 Nov 2021
Edited: Adam Danz on 17 Nov 2021
What Matlab release are you using?
I'm assuming daily_sm.DT contains datetime values. Does year(daily_sm.DT) throw an error?
Or maybe you have a variable named "year" which is preventing use of the function of the same name.

Sign in to comment.

Categories

Find more on Dates and Time in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!