Round elements in a table while simultaneously having titles?
21 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I want to simultaneously have tables were the elements inside are rounded, while also having a title and labels for the rows.
'title' | var1 | var2 | var3
'row1' | .123 .421 .021
'row2' | .321 .231 .231
Without rounding I can create a table with the following syntax:
TableName = ['row1','row2'];
T = table(var1, var2, var3, 'RowNames',TableName)
But to round, it seems like I need to use the function varfun:
TableName = ['row1','row2'];
T = table(var1, var2, var3, 'RowNames',TableName)
LOGtable = varfun(@(var) round(var, 4), T)
But in doing so I lose the 'RowNames' and title options in the previous table.
How should I solve this?
1 commentaire
Réponses (2)
Steven Lord
le 18 Déc 2018
Make a sample table.
t1 = array2table(rand(4, 3), ...
'VariableNames', {'var1', 'var2', 'var3'}, ...
'RowNames', {'x1', 'x2', 'x3', 'x4'})
Operate on a copy so you can compare with the original.
t2 = t1;
Assuming the contents of the variables in t1 can be concatenated together (ideally they're the same type, as they are in this example) operate on the Variables property of the table and put the result back in the Variables property of that same table.
t2.Variables = round(t2.Variables, 2)
1 commentaire
Steven Lord
le 2 Oct 2021
Since someone linked to this answer I want to add one more piece of information. If the variables in your table are not all the same type, you can use varfun to operate on just the numeric variables.
load patients
P = table(LastName, Height, Weight);
P.Density = P.Weight./P.Height;
head(P)
% Only operate on the numeric variables
P2 = varfun(@(x) round(x, 2), P, 'InputVariables', @isnumeric);
% Add back in the LastName variable
P2 = addvars(P2, P.LastName, 'Before', 1, 'NewVariableNames', 'LastName');
head(P2)
Cris LaPierre
le 13 Déc 2018
You could round first, as mentioned:
T1 = table(round(var1,4), round(var2,4), round(var3,4), 'RowNames',TableName)
You could create the table, round it, and then add the row and variable names
T2 = table(var1, var2, var3)
LOGtable = varfun(@(var) round(var, 4), T2);
LOGtable.Properties.RowNames = TableName;
LOGtable.Properties.VariableNames = {'var1','var2','var3'};
Another option is:
var = round([var1, var2, var3],4);
T3 = table(var,'RowNames',TableName);
T3 = splitvars(T3)
The last doesn't quite recreate the variable names, so you could again set them like you do in LOGtable.
Perhaps not what you are hoping for, but the best way I can think of.
1 commentaire
Peter Perkins
le 18 Déc 2018
array2table would be a better way to turn round([var1, var2, var3],4) into a table.
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!