How do I add rows to a table in a for loop?
Afficher commentaires plus anciens
I want to figure out how to take data from a list of tab-delimited .txt files of indeterminate length with formats like this:
Test Number Result
First test 1
First test 8
First test 3
First test 4
Test Number Result
Second test 201
Second test 208
Second test 203
Second test 204
And produce a table like this:
First 1 8 3 4
Second 201 208 203 204
filePattern = fullfile(myFolder, '*.txt'); % Change to whatever pattern you need.
theFiles = dir(filePattern);
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(theFiles(k).folder, baseFileName);
usableTable = readtable (fullFileName);
choppedTable = usableTable(:,["Test","Result"])
punyTable = choppedTable (1, "Test")
punyTable
SecondChopTable = choppedTable(:, "Result")
LongRow = rows2vars(SecondChopTable)
NewRow = [punyTable, LongRow]
NewRow.OriginalVariableNames = []
NewRow = vertcat(NewRow{i,:});
end
My problem is that, try as I might, I can't get NewRow to add rows onto the end of a table.
3 commentaires
Stephen23
le 23 Jan 2023
Is that one data file or two? It would be much easier to answer this, if you simply uploaded a sample data file or two.
"addpath '\\myfiles.campus.edu\alister\Sandbox' %adds where the files are"
Do not add folders of data files to the MATLAB search path. The search path should be for code only.
"myFolder = '\\myfiles.campus.edu\alister\Sandbox' % creates new folder"
That line of code does not create any folder.
"some kind of wonky BS that I don't understand. What I think is happening here is that this is somehow turning this into a real table function (whatever this means)"
The READTABLE documentation explains what it does. The phrase "real table function" exists only on this thread.
Réponses (2)
Try something like this —
T1 = array2table(magic(5))
for k = 1:3
NewRow = array2table(rand(1,5));
T1 = vertcat(T1,NewRow);
end
T1
.
4 commentaires
Alister
le 23 Jan 2023
Star Strider
le 23 Jan 2023
Déplacé(e) : Star Strider
le 23 Jan 2023
I first thought that unstack would work here, so I tried that first, and if the ‘Number’ entries differed, it still might be worth considering.
However, the desired result is simply a gropued and transposed concatenation of the original tables, so that is what I did —
T{1,:} = readtable('https://www.mathworks.com/matlabcentral/answers/uploaded_files/1272080/Sandbox1.txt');
T{2,:} = readtable('https://www.mathworks.com/matlabcentral/answers/uploaded_files/1272085/Sandbox2.txt');
T{3,:} = readtable('https://www.mathworks.com/matlabcentral/answers/uploaded_files/1272090/Sandbox3.txt');
Cat = T{1};
for k = 2:numel(T)
Cat = vertcat(Cat,T{k});
end
Cat
[G,ID] = findgroups(Cat.Test); % Identify Groups By 'Test'
Tally = accumarray(G,Cat.Result,[],@(x){x}); % Accumulate Results, Return As Cell Array
Out = cellfun(@(x)transpose(x),Tally, 'Unif',0); % Transpose Individual Results
Out = array2table(cell2mat(Out),'RowNames',ID) % Create Output Table
DR = readtable('https://www.mathworks.com/matlabcentral/answers/uploaded_files/1272095/Result.txt')
The ‘ID’ cell array could be used either as the first variable (use addvars for that) or as row names. I chose row names here.
This could even be simplified further, however I sense that it’s a ‘proxy problem’ for a different set of tables (and possibly a similar but different problem), so I left it as it is.
.
Alister
le 24 Jan 2023
Star Strider
le 24 Jan 2023
I can’t demonstrate that easily here, however the general guidance is in: Import or Export a Sequence of Files
I would import all of them to a cell array in a loop, as I did here manually (since the directory structure here is a bit more complex than would usually be encountered) and then use the approach I used here to process the data to produce the desired final result.
.
"... it keeps producing the tables I want, but not in the order I want, and I don't know how to fix this."
My guess (in lieu of your explanation) is that your filenames are numbered and you expect the file to be returned in numeric order. In that case you will need to sort the filenames alphanumerically. One way is to download my FEX submission NATSORTFILES, which was written to sort filenames into alphanumeric order:
In most cases it is very simple to include in your code:
P = '.'; % absolute/relative path to where the files are saved.
S = dir(fullfile(P,'*.txt'));
S = natsortfiles(S); % download here: https://www.mathworks.com/matlabcentral/fileexchange/47434-natural-order-filename-sort
for k = 1:numel(S)
F = fullfile(S(k).folder,S(k).name);
T = readtable(F);
S(k).data = T(:,["Test","Result"]);
end
T = vertcat(S.data);
[U,~,X] = unique(T.Test,'stable');
H = @(a) {num2cell(a.')};
C = splitapply(H,T.Result,X);
C = [U,vertcat(C{:})]
T = cell2table(C)
Your description is unclear about what data type you require the output to be, so I showed a few options for you.
Catégories
En savoir plus sur Spreadsheets dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!