Create new column in table from data across multiple columns
8 次查看(过去 30 天)
显示 更早的评论
I have a table with multiple events (P1, P2, N1, early P3, P3) listed in one column, ROI. There are several adjacent columns with latencies that have the same events in their titles. I would like to create a new column (Latencies) with the latencies in the adjacent columns extracted and matched the events in the ROI column. For example if the event under ROI is P1 then under the new column, Latencies, the data in the same row under P1_Max_Lat would be copied. I attached a sample table.
0 个评论
采纳的回答
Image Analyst
2021-11-4
Try this:
load('Example_table.mat')
[rows, columns] = size(sampletable)
tLatencies = table(zeros(rows, 1), 'VariableNames', {'Latencies'})
newTable = [sampletable, tLatencies]
for row = 1 : rows
% Get the event name.
event = newTable.ROI{row}
% Based on that, get the name of the column
% we need to look for to get the data.
columnName = sprintf('%s_Max_Lat', event)
% If that column is there, copy the number to the Latencies column.
if ismember(columnName, newTable.Properties.VariableNames)
% Get data from the appropriate column.
data = newTable.(columnName)(row)
% Put data into the latencies column
newTable.Latencies(row) = data;
else
fprintf('There is no column called %s in the table.\n', columnName);
end
end
3 个评论
Image Analyst
2021-11-4
Sure. I understand better now what you want and below is a more robust version that finds the first column that starts with the event string:
load('Example_table.mat')
[rows, columns] = size(sampletable);
tLatencies = table(zeros(rows, 1), 'VariableNames', {'Latencies'});
newTable = [sampletable, tLatencies];
[rows, columns] = size(newTable); % Update size.
variableNames = newTable.Properties.VariableNames;
for row = 1 : rows
% Get the event name.
event = newTable.ROI{row};
% Based on that, get the name of the column
% we need to look for to get the data.
foundIt = false;
for col = 1 : columns
if startsWith(variableNames{col}, event)
% Indicate that we found a column name that starts with the event name.
foundIt = true;
columnName = variableNames{col};
break;
end
end
if ~foundIt
% We did not find any column starting with the event name.
fprintf('There is no column starting with %s in the table.\n', event);
continue; % Skip the rest of the loop for this iteration only.
end
% If that column is there, copy the number to the Latencies column.
if ismember(columnName, newTable.Properties.VariableNames)
% Get data from the appropriate column.
data = newTable.(columnName)(row);
% Put data into the latencies column
newTable.Latencies(row) = data;
end
end
% Report the new table to the command window:
newTable
If this works, please "Accept this Answer". Thanks in advance. If not, let me know what row is bad.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Environment and Settings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!