Removing trailing end characters in a table

24 views (last 30 days)
Hi guys,
I am trying to eliminate last two characters of variable names in a table. This is how my table looks like now (exported table to csv file attached). Couldn't get the csv file to show output here in Matlab live for some reason. But anyways my var name in column looks like for example 'abc_01_1' 'abc_02_1'. What I want to do is eliminate last two charaters which can be '_1' or '_2' or '_3' or '_4' and so on to be able to compare this table with a master variable list which doesn't have those last characters to find any missing and add them to the table with 'NA' as it's value
data = readtable('list.csv','Delimiter',',');
mlist = readtable('masterlist.txt', 'Delimiter',',');
The things that I have tried so far is the erase function like this
match = ["_1","_2","_3","_4"];
sz = size(data);
for idx = 1:sz(1,:)
var = data.Var1(1:idx);
newvar = erase(var,match);
end
data.Var1 = newvar;
%setdiff Error's out because the variable names are not the same
diff = setdiff(mlist,data);
NA_cell = cell(size(diff));
NA_cell(:) = {'NA'};
diff = [diff NA_cell];
%Then use vertcat to add 'diff' and 'data' together which wil be the final table with actual and missing.
But erase function elimitates all the instances of the charaters found in match so that didn't work out. Like if 'abc_01_1' then output of erase will be just 'abc0'.
I was also looking into strip function
newvar = strip(var,'right','_1') %But strip only works on removing one character from right so this didn't work either
Is there any other way to do this?
Thanks,

Accepted Answer

Cris LaPierre
Cris LaPierre on 6 Jul 2022
You could use extractBefore and strlength. This works with string data, so I import text as stings.
data = readtable('https://www.mathworks.com/matlabcentral/answers/uploaded_files/1056935/list.csv',...
'Delimiter',',','TextType','string')
data = 98×2 table
Var1 Var2 __________ ____ "abc_88_4" 210 "abc_75_3" 170 "abc_76_4" 160 "abc_80_4" 160 "abc_59_3" 130 "abc_60_3" 130 "abc_81_4" 130 "abc_85_4" 130 "abc_61_3" 120 "abc_62_3" 120 "abc_63_3" 120 "abc_33_2" 110 "abc_58_3" 110 "abc_77_4" 110 "abc_82_4" 110 "abc_86_4" 110
% Set the position to the length of each string - 1
data.Var1 = extractBefore(data.Var1,strlength(data.Var1)-1)
data = 98×2 table
Var1 Var2 ________ ____ "abc_88" 210 "abc_75" 170 "abc_76" 160 "abc_80" 160 "abc_59" 130 "abc_60" 130 "abc_81" 130 "abc_85" 130 "abc_61" 120 "abc_62" 120 "abc_63" 120 "abc_33" 110 "abc_58" 110 "abc_77" 110 "abc_82" 110 "abc_86" 110

More Answers (0)

Categories

Find more on Cell Arrays in Help Center and File Exchange

Products


Release

R2017b

Community Treasure Hunt

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

Start Hunting!