How do I sum the values of sections of a table?
19 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Macy
el 8 de Feb. de 2023
Respondida: Tushar Behera
el 8 de Feb. de 2023
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 comentarios
Respuesta aceptada
Tushar Behera
el 8 de Feb. de 2023
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 comentarios
Más respuestas (1)
Voss
el 8 de Feb. de 2023
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 comentarios
Ver también
Categorías
Más información sobre Numeric Types en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!