Adding a new column in table based on matching number from other columns in the same table
2 次查看(过去 30 天)
显示 更早的评论
Hi,
I am trying to create an additional column of 'choice', which should contain either 'air,'trian','bus', 'car' depending upon where 1 has appeared in their respective column for given row.
I am unable to write the code that searches for 1 in columns in AIR, Train, Bus, Car and append the name of the column (e.g., car in first row) to new column named as 'choice'.
Any help would be highly appreciated.
Best wishes,
0 个评论
采纳的回答
nick
2024-9-13
Hi Yasir,
You can use logical indexing function to allocate the value in column 'choice'.
You can iterate over each row, check which column has the value 1, and then assign the corresponding column name to the new column 'choice'. Here's a MATLAB script that illustrates the same :
T = readtable('mode_choice');
options = {'AIR', 'Train', 'Bus', 'Car'};
% Preallocate the 'choice' column with empty strings
T.choice = strings(height(T), 1);
for i = 1:height(T)
% Find the column with value 1
idx = find([T.AIR(i), T.Train(i), T.Bus(i), T.Car(i)] == 1);
% Check if any column contains 1
if ~isempty(idx)
T.choice(i) = options{idx};
end
end
disp(T);
You can refer to the following documentation to learn more about 'logical indexing':
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!