remove rows in table based on different string across columns

1 visualización (últimos 30 días)
DavidL88
DavidL88 el 6 de Nov. de 2021
Editada: DavidL88 el 7 de Nov. de 2021
How do I remove any row in which one column contains either 11_right OR 21_right and the other column contains earlyP3? Drafted below code but doesn't work. I attach a sample table.
T(contains(string(T{:,2}),'11_right') & string(T{:,3}),'earlyP3') = [];
T(contains(string(T{:,2}),'21_right') & string(T{:,3}),'earlyP3') = [];

Respuesta aceptada

Dave B
Dave B el 7 de Nov. de 2021
Editada: Dave B el 7 de Nov. de 2021
You have a couple of bugs:
  • You need to write contains twice: it's not contains(thing,otherthing) & thing2,otherthing2 but instead contains(thing,otherthing) & contains(thing2,otherthing2)
  • You need a to tell MATLAB that you want the whole row, that means specifying a ,: when you provide the rows. That is T(rows,columns) and columns is all (even though you can't remove a partial row in a table).
A few tips:
  • contains is probably not exactly what you want here, but maybe suitable enough for your purposes. contains will match 11_right and also 311_right if you had that, because the latter 'contains' the former. Consider using strcmp or ismember for the more precise match. Even though it's maybe irrelevant for this dataset, one day you might copy this code and then you'll have potential for a scary hidden bug.
  • It's easier with this kind of logic to define some index variables, that can help you debug a little. Here I broke it into 2 variables, but you could even break it into 3 (making the earlyP3 one a variable too). I wasn't creative with the names!
  • You don't need to force your chars into strings as MATLAB will figure it out when you say contains, nothing wrong with this though!
load sampleT.mat
preheight=height(sampleT);
ind1 = contains(sampleT.Outcome, '11_right') & contains(sampleT.ROI, 'earlyP3');
ind2 = contains(sampleT.Outcome, '21_right') & contains(sampleT.ROI, 'earlyP3');
sampleT(ind1 | ind2,:) = [];
postheight = height(sampleT);
fprintf('%d rows removed\n', preheight - postheight)
5 rows removed
  1 comentario
DavidL88
DavidL88 el 7 de Nov. de 2021
Editada: DavidL88 el 7 de Nov. de 2021
Thank you Dave. Thanks for the code and the advice.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by