how to rename columns with names like Var2_1, Var2_2...?
2 views (last 30 days)
Show older comments
Writing data to an xlsx file I get this:
Var1 Var2_1 Var2_2 Var2_3
01-May-2024 2213 98 111
How can I rename Var2_n ?
renamevars and output_data.Properties.VariableNames doesn't work..
Here is my code (thanks a lot for each hint!):
% Read data from 'data.xlsx'
data = readtable('data.xlsx');
% Get unique dates
unique_dates = unique(data{:, 1}); % Assuming the date column is the first column in the table
% Initialize output table
output_data = table();
% Loop through each unique date
for i = 1:length(unique_dates)
date_data = data(strcmp(data{:, 1}, unique_dates{i}), :);
% Calculate sum of numbers for each date
sum_numbers = floor(sum(date_data{:, 3:5}, 1));
% Create a new row with Date and sum_numbers
new_row = {unique_dates{i}, sum_numbers};
% Append the new row to the output table
output_data = [output_data; new_row];
end
% Write output data to 'data-new.xlsx'
writetable(output_data, 'data-new.xlsx');
2 Comments
Yash
on 8 May 2024
Hi Harald,
I am unable to understand the issue that you are facing while using "renamevars". I tried it, and it works as expected.
Kindly refer to the example below:
tbl = table([1;11;111;1111],[2;22;222;2222],[3;33;333;3333],[4;44;444;4444],'VariableNames',["Var1" "Var2_2" "Var2_3" "Var2_4"])
tbl = renamevars(tbl,["Var2_2" "Var2_3" "Var2_4"],["Var2" "Var3" "Var4"])
To better assist you, kindly let us know the issue that you are encountering.
Accepted Answer
Star Strider
on 8 May 2024
Edited: Star Strider
on 8 May 2024
Probably the easiest way:
data.Properties.VariableNames(2:end) = {'Var2','Var3','Var4'};
Example —
data = array2table(rand(2,4), 'VariableNames',{'Var1','Var2_1','Var2_2','Var2_3'})
data.Properties.VariableNames(2:end) = {'Var2','Var3','Var4'}
You can also use that approach to rename all of them, if you want to.
.
EDIT — Corrected typogrpahical errors, added information.
0 Comments
More Answers (1)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!