How to do monthly average in a Table?
Show older comments
Hi,
I have a Matlab Table that has 3 columns. The first column is dates, the 2nd column is Term (integer number), and the 3rd column is prices (double).
The columns are: Dates Terms Prices
I want to create a new table, that the the dates of only the first of each month, and have the average price for each month.
I thought it should be easy to do, as I can do it in Excel pivot table by hand.
How to do that in Matlab? I imagine Matlab should make it easier. Besides, I have many such Excel so I want to do it more efficiently.
Thanks,
Jennifer
Accepted Answer
More Answers (1)
Brendan Hamm
on 3 Aug 2015
If you have the Statistics and MAchine Learning Toolbox, this can be done quite easily. For simplicity I will assume your Table T has the variables: Date, Terms and Prices. What we want to do is use the Month as a grouping variable. We can get the month from a datetime with the month function:
mth = month(T.Dates); % Numeric Values (optional input 'name' will give the full name)
Now we want to calculate the mean for each month which is easy to do with grpstats which will calculate statistics of its first input, grouped by the second input:
doc grpstats
[monthlyPriceMean,groupName] = grpstats(T.Prices,mth,{'mean','gname'});
monthTable = table(groupName,monthlyPriceMean); % Place in a table
You could do the same thing with the Terms. If you really want to apply this and get a table back out immediatelly, you could always use this in conjunction with varfun.
7 Comments
JFz
on 3 Aug 2015
JFz
on 3 Aug 2015
JFz
on 3 Aug 2015
Edited: Walter Roberson
on 4 Aug 2015
Walter Roberson
on 4 Aug 2015
month() was introduced in R2014b. The Statistics And Machine Learning Toolbox was not named that until R2015a; before that it was the Statistics Toolbox, so if you do not have month() then you do not have the modern version of the Statistics And Machine Learning Toolbox. However, grpstats() was introduced in R2014a so there is still a possibility that you have the routine if your Statistics Toolbox is at least that old.
A workaround to get the month number is:
date_vectors = datevec(T.dates);
mth = date_vectors(:,2);
Brendan Hamm
on 4 Aug 2015
Edited: Brendan Hamm
on 4 Aug 2015
Thanks Walter. She may indeed still have the month function, but it only works on datetimes and not on datestrings which is what she has. For grouping by term just pass in T.Term as your grouping variable. It will automatically use the unique string values as groups.
JFz
on 6 Aug 2015
Walter Roberson
on 6 Aug 2015
I misread the release notes about when grpstats was introduced; when I look again I can no longer say when it was introduced.
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!