Converting multiple table variables from string to categorical data

6 次查看(过去 30 天)
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

回答(1 个)

Tim leonard
Tim leonard 2015-2-12
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 个评论
Dhruv Ghulati
Dhruv Ghulati 2015-12-18
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 2015-12-18
Please start your own question (you can link to this one to add context) rather than hijacking somebody's else.

请先登录,再进行评论。

类别

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