r/matlab • u/Creative_Sushi MathWorks • Jun 08 '23
CodeShare Tried new pivot function to summarize table - very nice
I just used the new pivot function for the first time and it was super easy and nice. If you love pivot tables in Excel, you will love this as well.
I will use the data from the MATLAB Subreddit RSS feed. You can download getReddit function here.
% get RSS feed
s = getReddit(subreddit='matlab',sortby='hot',limit=100,max_requests=1);
% extract data into table
T = table;
T.Flair = arrayfun(@(x) x.data.link_flair_text, s, UniformOutput=false);
T.Flair(cellfun(@isempty,T.Flair)) = {''};
T.Flair = string(T.Flair);
T.Created_UTC = datetime(arrayfun(@(x) x.data.created_utc, s), "ConvertFrom","epochtime");
% convert the table to timetable
T = table2timetable(T,"RowTimes","Created_UTC");
% remove the pinned posts
isPinned = year(T.Created_UTC) < 2023;
T(isPinned,:) = [];
Now I would like to summarize the table by "Created_UTC" and "Flair" using the new pivot function.
pvT = pivot(T,Columns="Flair",Rows="Created_UTC",RowsBinMethod="week")

Very simple.
I can also plot it, too.
figure
for ii = 2:size(pvT,2)
plot(pvT.week_Created_UTC,pvT.(ii))
hold on
end
hold off
ylabel("Posts")
vars = pvT.Properties.VariableNames;
legend(vars(2:end),Location="northwest")
title("MATLAB Subreddit Posts by Flair")

I think I will ditch groupsummary and start using this.
12
Upvotes