Converting multiple table variables from string to categorical data

7 Ansichten (letzte 30 Tage)
Jared
Jared am 28 Mär. 2014
Kommentiert: Guillaume am 18 Dez. 2015
I've figured out how to use the categorical function to convert a single table variable (i.e., a single column of table data) to categorical data using the table.variable=categorical(table.variable) method but is there not a way to convert multiple variables/columns from string to categorical with a single command?
Thanks,
JK

Antworten (1)

Tim leonard
Tim leonard am 12 Feb. 2015
I'd love to know if this is possible as well. This is the best I can figure out, but still not really at all elegant.
%make table
tblIn= table({'cat';'dog';'bird'},{'bat';'rat';'sat'},(1:3)')
%which cols to convert
cellOfColumnNames = {'Var1','Var2'}
tblOut = [tblIn(:,~ismember(tblIn.Properties.VariableNames,cellOfColumnNames))...
varfun(@categorical,tblIn,'inputvariables',cellOfColumnNames)];
% or, unpacked a little bit:
newTable = varfun(@categorical,tblIn,'inputvariables',cellOfColumnNames);
tblOut = [tblIn(:,~ismember(tblIn.Properties.VariableNames,cellOfColumnNames))...
newTable];
  2 Kommentare
Dhruv Ghulati
Dhruv Ghulati am 18 Dez. 2015
This is a great answer. I tried to use the same thing for the function str2double, but I got an error
Error using table (line 253) All variables must have the same number of rows.
Error in table/varfun (line 220) b = table(b{:},'VariableNames',b_varnames);
continousVars = {'artists_paying_for', 'bookmarks','connected_ga','connected_fb',...
'connected_itunes','free_artists','subscribed_artists','usersincompany',...
'companyartistspaidfor','sincelastcontacted','sincelastheardfrom','sincefirstseen',...
'sincesignedup','sincecompanylastseen','sincecompletedsetup','sinceusercreated',...
'sinceaccountcreated','sincecompanycreated'};
newTable = varfun(@str2double,cleanNBS,'inputvariables',continousVars);
T = [cleanNBS(:,~ismember(cleanNBS.Properties.VariableNames,catVars))...
newTable];
Any ideas?
Guillaume
Guillaume am 18 Dez. 2015
Please start your own question (you can link to this one to add context) rather than hijacking somebody's else.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Tables finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by