Dummy Variable ased on categorical vars in table

10 vues (au cours des 30 derniers jours)
Matthew Worker
Matthew Worker le 3 Nov 2018
hi everyone! I'm tying to create a dummy variable in a table based on two categorical variables. My table contains numerical and categorical variables. I now want to add an additional column with values either zero or one. I have a 27x7 table. My code goes as follows:
Data.DV = zeros(27,1)
for x = 1:27
if Data.BS== 'Total assets' & Data.Bank =='Bank X'
Data.DV =1;
else Data.DV =0;
end
end
However, when I try this I receive the error message 'To assign to or create a variable in a table, the number of rows must match the height of the table.' Could you help me explain how to generate this new dummy? Many thanks ahead! Lea

Réponses (3)

Jeff Miller
Jeff Miller le 3 Nov 2018
Since you are using a loop on x to go through the table one row at a time, you have to index the table variables BS, bank, and DV to select out one row at a time, like this:
Data.DV(x) = 1;
Another problem is that you can't compare strings with ==. Instead, you have to use strcmp().

Matthew Worker
Matthew Worker le 4 Nov 2018
Thanks!! Now I tried
Data.DV = zeros(27,1)
for x = 1:27
if strcmp(Data(x).BS, 'Total assets')
Data.DV(x) =1;
else Data.DV(x) =0;
end
end
But it still doesn't work. Instead, I get two new error messages:
"Error using tabular/subsrefParens (line 15) You cannot subscript a table using linear indexing (one subscript) or multidimensional indexing (three or more subscripts). Use a row subscript and a variable subscript.
Error in tabular/numArgumentsFromSubscript (line 59) x = subsrefParens(t,s(1));"
  1 commentaire
Jeff Miller
Jeff Miller le 4 Nov 2018
Use Data.BS(x) instead of Data(x).BS

Connectez-vous pour commenter.


Peter Perkins
Peter Perkins le 6 Nov 2018
Don't use a loop. It's completely unnecessary. And make BS and Bank categorical variables. Then all you need is
Data.DV = (Data.BS == 'Total assets') & (Data.Bank =='Bank X');
That's it.

Catégories

En savoir plus sur Tables dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by