consolidating table from years to decades

1 次查看(过去 30 天)
I have a table of bridges with averages by year, I am trying to consolidate this data to be by decade so the averages of the data in the second column reduced to average of that data by 1990s, 19070s etc.
T = readtable("bridgedata.xlsx");
years = unique(T(:,'YEAR_BUILT'));
G = findgroups(T.YEAR_BUILT);
avgNumLanes = splitapply(@mean,T.TRAFFIC_LANES,G);
avgNumLanes = table(avgNumLanes);
numLanesByYear = [years,avgNumLanes];
avgMaxSpanLength = splitapply(@mean,T.MAX_SPAN_LEN_MT,G);
avgMaxSpanLength = table(avgMaxSpanLength);
spanLengthByYear = [years,avgMaxSpanLength];
avgLength = splitapply(@mean,T.STRUCTURE_LEN_MT,G);
avgLength = table(avgLength);
lengthByYear = [years,avgLength];
avgByYear = [avgNumLanes,avgMaxSpanLength,avgLength];
  1 个评论
Stephen23
Stephen23 2022-4-4
编辑:Stephen23 2022-4-4
Create a new variable/column in the table for the decade, e.g. DEC_BUILT, and use that to group the table data.
You might consider using GROUPSUMMARY rather than repeating SPLITAPPLY.
If you want more help please upload a sample file by clicking the paperclip button.

请先登录,再进行评论。

回答(1 个)

Anurag
Anurag 2023-10-25
Hi David,
I understand that you want to have your averages computed using “decades” as compared to using “years”. Refer to the following modifications in the code provided by you for doing the same:
T = readtable("bridgedata.xlsx");
% Extract the year information from the YEAR_BUILT column
years = year(T.YEAR_BUILT);
% Define the decades you want to group by
decades = floor(years / 10) * 10;
% Group the data by decade
G = findgroups[NM3] (decades);
% Compute the averages for each attribute
avgNumLanes = splitapply[NM4] (@mean, T.TRAFFIC_LANES, G);
avgMaxSpanLength = splitapply(@mean, T.MAX_SPAN_LEN_MT, G);
avgLength = splitapply(@mean, T.STRUCTURE_LEN_MT, G);
% Create a table with decades and corresponding averages
avgByDecade = table(decades, avgNumLanes, avgMaxSpanLength, avgLength);
% Rename the variable names for clarity
avgByDecade.Properties.VariableNames = {'Decade', 'AvgNumLanes', 'AvgMaxSpanLength', 'AvgLength'};
Find the relevant documentations links for the functions used above here:
Hope this helped.
Regards,
Anurag

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by