Table: how to extract rows that contain a certain string and put those values into a new column?

31 vues (au cours des 30 derniers jours)
eg if my table looks like this:
column 1 column 2 column 3 column 4
083282 128033 houseman eiuefief
983298 120942 penhouse wfdwhf
239832 108128 random idqiydqy
Say I want to extract all column 3 rows that contain the string "house" and put these values into column 5 so they look like this:
column 1 column 2 column 3 column 4 column 5
083282 128033 houseman eiuefief houseman
983298 120942 penhouse wfdwhf penhouse
239832 108128 random idqiydqy
Because column 5 has to have the same height as the other columns, the rows that don't contain the column can have NaN, 0, missing or something else to indicate that they don't contain anything:
column 1 column 2 column 3 column 4 column 5
083282 128033 houseman eiuefief houseman
983298 120942 penhouse wfdwhf penhouse
239832 108128 random idqiydqy NaN

Réponse acceptée

Walter Roberson
Walter Roberson le 21 Mar 2020
YourTable.NewVariableName = string(nan(height(YourTable, 1)));
mask = contains(YourTable{:,3}, "house");
YourTable.NewVariableName(mask) = YourTable{mask,:3};
  2 commentaires
Xuan Yee
Xuan Yee le 21 Mar 2020
Thank you so much!
Last line of code shouldn't have the colon.
YourTable.NewVariableName(mask) = YourTable{mask,3};
Walter Roberson
Walter Roberson le 21 Mar 2020
You are correct, that was a typing mistake on my part.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Characters and Strings 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