Create new column in table
15 views (last 30 days)
Show older comments
Hello, this seems like a stupidly easy problem but I cannot find any way to do it
Currently I have a table with three columns. I want to add three additional columns to the table, each of which contain certain values from the second column. In this case, column 4 should contain all the elements in column 2 that start with "E", column 5 should contain all the elements in column 2 that start with "I", co;umn 6 should contain all the elements in column 2 that start with "P"
And then these new columns need to align with their respective values in columns 1 and 3 of the table
How would I do something like this? I've attached a screenshot of the table that I want to transform
Thank you
9 Comments
Adam Danz
on 10 Jul 2019
If you read about the first input to fitlme(), the table is "input data, which includes the response variable, predictor variables, and grouping variables, specified as a table or dataset array."
Grouping variables (<-- see link for more info) can be a character array or a cell array of characters which is exactly what my answer demonstrates. Have you tried that yet?
Answers (1)
Adam Danz
on 9 Jul 2019
Edited: Adam Danz
on 10 Jul 2019
Here's a demo that creates a similar table to the table you shared in the png file. It then shows how create indices that find rows of the table where the "Type" begins with "E" and "I" (you can add the "P" index).
% Create table
TIME = zeros(20,1);
Type = cellstr([("E"+(1:10))';("I"+(1:10))']);
LogImpedance = rand(20,1)*4;
T = table(TIME,Type,LogImpedance);
% Create indices for each Type
firstChar = cellfun(@(x)x(1),T.Type);
isE = firstChar == 'E';
isI = firstChar == 'I';
Use the indices to select rows of the table
For example, if you want to take the sum of "LogImpedance" for all "E" types,
sum(T.LogImpedance(isE))
Append the table with duplicate data if you must
This section shows how to append the table with duplicate data as you described (probably unnecessary).
% (Assuming the first block of code above has been executed)
% Create new columns
newColumns = cell(size(T,1),2); % Change '2' to add more or less columns
newColumns(isE,1) = T.Type(isE);
newColumns(isI,2) = T.Type(isI);
Tappend = array2table(newColumns,'VariableNames',{'isE','isI'});
% Append table
Tnew = [T,Tappend];
Appending the table with a categorical column (**GROUPING VARIABLE**)
% (Assuming the first block of code above has been executed)
Tnew = [T, table(firstChar,'VariableNames',{'category'})]
0 Comments
See Also
Categories
Find more on Tables in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!