Transferring variable names from one table to another

I'm trying to use the variable names of one of my tables in another new table, but keep getting an error saying "Error using table The VariableNames property is a cell array of character vectors. To assign multiple variable names, specify names in a string array or a cell array of character vectors" even though I have the variable names saved in a cell array. I have tried making varnames a string array, used a for loop to copy all the names to varnames, concatenated them vertically instead of horizontally just for the heck of it, but I can't seem to figure it out. This is my code:
varnames = cell.empty;
varnames = DataFinal.Properties.VariableNames
T = table('VariableNames',{varnames}, 'RowNames', {'A','B','C'})

 采纳的回答

varnames = DataFinal.Properties.VariableNames
T = table('VariableNames',varnames, 'RowNames', {'A','B','C'})

8 个评论

I think you are going to have trouble with the RowNames. There should be one row name for each row, but you are creating a table with no rows.
Thank you! Realized I had to define the sizes and thus the variable types and so on, ended up with this, and it works! Thanks again!
vartype = cell(1,49)
for j=1:49
vartype{1,j} = 'double'
end
varnames = PatientDataFinalwithv11.Properties.VariableNames(2:50)
T = table('Size',[12 49],'VariableTypes', vartype,'VariableNames',varnames, 'RowNames', {'Intercept Es...'})
Hello,
I tried this method on MATLAB R2020B and received the following error:
Error using table (line 335)
The VariableNames property must contain one name for each variable in the table.
The varnames variable I created is a cell array with names from a table I imported with readtable. So, I believe I've followed all of the prerequisits for the two lines of code shown above to work. Any thoughts?
N = 49;
vartype = repmat({'double'}, 1, 49);
varnames = "MyVar" + (1:N);
T = table('size', [12 N], 'VariableTypes', vartype, 'VariableNames', varnames);
whos T
Name Size Bytes Class Attributes T 12x49 16331 table
If you have a list of variable names and you want to allocate a table of that size, then (for example)
varnames = "MyVar" + (1:randi(50)); %variable names read from table
nrows = 7; %for example
N = length(varnames);
vartype = repmat({'double'}, 1, N);
T = table('size', [nrows N], 'VariableTypes', vartype, 'VariableNames', varnames);
whos T
Name Size Bytes Class Attributes T 7x28 8533 table
Thanks. It seems that the use of repmat only allows one data type. I suppose that if I need to have columns of different data types, I can just change those columns after the table is created, right?
repelem({'double', 'categorical', 'double'}, 1, [17, 2, 11])
for example for the case of 17 double followed by 2 categorical followed by 11 double

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Tables 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by