How do I sum the values of sections of a table?
19 次查看(过去 30 天)
显示 更早的评论
Hi there. I have this data, for which I created a new vector called schoolyear. How do I sum the total number of students for each schoolyear and save each value into a new vector or matrix?
So for example, the new vector totalstudents should read: 50, 66.
One suggestion I have been given is to use a for loop with possibly an if/then.
Note this is a sample of a much larger data set.
Thank you.
clc;
close all;
clear all;
table_a = readtable('Data1.xlsx');
%Create the new vector, schoolyear
for i = 1:height(table_a)
if table_a.month(i)>=8
schoolyear(i) = table_a.year(i) + 1;
else
schoolyear(i) = table_a.year(i);
end
end
table_a.schoolyear = schoolyear(:)
0 个评论
采纳的回答
Tushar Behera
2023-2-8
Hi Macy,
I believe you want to group the students by the year and find the total.
This can be acheived by using the function "splitapply". This function apply a function to a group of data. For example:
clc;
close all;
clear all;
table_a = readtable('Data1.xlsx');
%Create the new vector, schoolyear
for i = 1:height(table_a)
if table_a.month(i)>=8
schoolyear(i) = table_a.year(i) + 1;
else
schoolyear(i) = table_a.year(i);
end
end
table_a.schoolyear = schoolyear(:)
g=findgroups(table_a.schoolyear)%find the groups in the data
grouped_students_total= splitapply(@sum, table_a.students, g);%get the sum from the groups
Here in "grouped_students_total" you will find your desired result. To know more about "splitapply" you can follow the following documentation:
I hope this resolves your query.
Regards,
Tushar
0 个评论
更多回答(1 个)
Voss
2023-2-8
table_a = readtable('Data1.xlsx');
%Create the new vector, schoolyear
for i = 1:height(table_a)
if table_a.month(i)>=8
schoolyear(i) = table_a.year(i) + 1;
else
schoolyear(i) = table_a.year(i);
end
end
table_a.schoolyear = schoolyear(:);
Here's one way:
table_summary = groupsummary(table_a,'schoolyear',@sum,'students')
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Numeric Types 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!