remove rows in table based on different string across columns

1 回表示 (過去 30 日間)
DavidL88
DavidL88 2021 年 11 月 6 日
編集済み: DavidL88 2021 年 11 月 7 日
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') = [];

採用された回答

Dave B
Dave B 2021 年 11 月 7 日
編集済み: Dave B 2021 年 11 月 7 日
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 件のコメント
DavidL88
DavidL88 2021 年 11 月 7 日
編集済み: DavidL88 2021 年 11 月 7 日
Thank you Dave. Thanks for the code and the advice.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by