remove rows in table based on different string across columns

조회 수: 2 (최근 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 CenterFile Exchange에서 Tables에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by