MATLAB Answers

Create new column in table based on another column value

8 views (last 30 days)
I have a table with the list of User IDs and I used "Groupummary" to determine the number of occurences of each ID. My table T:
ID Occurrences
123 9
345 1
234 3
I need to create another column in the table to mark the ID as "unique" or not based on the number of occurrences.
Expected output:
ID Occurrences Unique
123 9 No
345 1 Yes
234 3 No
I'm using the following code, but I get error saying the number of rows should match the length of table:
if T.Occurences> 1
T.Unique = "No";
else
T.Unique = "Yes";
end
How do I check the length of table and fill the "Unique" column for each corresponding cell?

  0 Comments

Sign in to comment.

Accepted Answer

Steven Lord
Steven Lord on 26 Nov 2020
Let's start with a sample table.
T = table([123; 345; 234], [9; 1; 3], 'VariableNames', ["ID", "Occurrences"])
T = 3x2 table
ID Occurrences ___ ___________ 123 9 345 1 234 3
Fill in the Unique variable with a default value.
T.Unique = repmat("No", height(T), 1)
T = 3x3 table
ID Occurrences Unique ___ ___________ ______ 123 9 "No" 345 1 "No" 234 3 "No"
Change the value of the Unique variable based on the contents of the Occurrences variable.
T.Unique(T.Occurrences == 1) = "Yes"
T = 3x3 table
ID Occurrences Unique ___ ___________ ______ 123 9 "No" 345 1 "Yes" 234 3 "No"

More Answers (1)

VBBV
VBBV on 26 Nov 2020
Edited: VBBV on 26 Nov 2020
clear
ID = [123 345 234]
Occurences = [9 1 3]
T = table(ID',Occurences','VariableNames',{'ID','Occurences'});
for i = 1:length(ID)
if T.Occurences(i) > 1
Unique{i} = 'No';
else
Unique{i} = 'Yes';
end
end
T = table(ID',Occurences',Unique','VariableNames',{'ID','Occurences','Unique'})

Community Treasure Hunt

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

Start Hunting!