필터 지우기
필터 지우기

merging columns to a table from multiple text files

조회 수: 5 (최근 30일)
Franziska Motka
Franziska Motka 2022년 6월 16일
댓글: Franziska Motka 2022년 6월 16일
Hi everyone,
I'm trying to create a for loop in order to merge the 8th column of several text files to one table.
files = dir('*.txt');
for i = 1:length(files)
files(i).name
tables = readtable(files(i).name)
XXX
end
Thank your for any help!
  댓글 수: 2
Walter Roberson
Walter Roberson 2022년 6월 16일
To confirm, the resulting table should contain exactly one variable, and that will be the merged column 8? Or should there be additional variables in the table?
Franziska Motka
Franziska Motka 2022년 6월 16일
No, I would also need a column for the code for each participant, thanks for asking!

댓글을 달려면 로그인하십시오.

답변 (1개)

Sarah Gilmore
Sarah Gilmore 2022년 6월 16일
Hi Franziska,
You could collect the eith column from each file and temporarily store the data in a cell array before constructing your final table.
files = dir("*.txt");
numTotalFiles = numel(files);
columnData = cell(1, numTotalFiles);
for i = 1:numTotalFiles
temp = readtable(files(i).name);
columnData{i} = temp.(8);
end
finalTable = table(columnData{:});
finalTable will contain the 8th column from each file.
Also, you may want to consider calling detectImportOptions to ensure each file is read in the same way (I am assuming the files have the same structure). readtable calls detectImportOptions by default if an Import Options object is not passed in order to determine how to import the data. Here's how you could do this:
files = dir("*.txt");
opts = detectImportOptions(files(1).name);
% Tell readtable to import only the 8th column
opts.SelectedVariableNames = 8;
numTotalFiles = numel(files);
columnData = cell(1, numTotalFiles);
for i = 1:numTotalFiles
temp = readtable(files(i).name, opts);
columnData{i} = temp.(1);
end
finalTable = table(columnData{:});
  댓글 수: 9
Sarah Gilmore
Sarah Gilmore 2022년 6월 16일
Hi Franziska,
Sorry again. I should have specified the VariableNames name-value pair as a char array instead of a string.
finalTable = table(columnData{:}, 'VariableNames', variableNames);
table requires parameter names to be specified as character vectors. Most other functions do not have this requirement. You can also use this syntax if you prefer:
finalTable = table(columnData{:}, VariableNames=variableNames);
I wasn't sure what release you were using, so I didn't want to suggest the syntax above since it was only introduced in R2021a. Either one of these lines should resolve the error.
Franziska Motka
Franziska Motka 2022년 6월 16일
Fantastic, it works. Thank you so much for all your help!!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 String Parsing에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by