How to change strange cell array within a table to double or categorical array

2 ビュー (過去 30 日間)
Flynn McGuire
Flynn McGuire 2020 年 6 月 26 日
回答済み: dpb 2020 年 6 月 28 日
I have some columns within a table that are labeled as cells that contain both NaN's and "Checked" (a categorical).
Please see the attach screen shot.
How to I change those columns to either a categorical array or to a numeric array with "checked" as 1's?
Thanks!

採用された回答

dpb
dpb 2020 年 6 月 28 日
Well, it'd be easier to be sure if could actually know for sure what the data storage is, but guessing on account of the " surrounding the string data, I created a dummy cell array as
LS=num2cell(nan(10,1)); % start w/ NaN
LS(randperm(10,3))={"Checked"}; % set some random cells to "Checked"
% Result for this invocation was
>> LS
LS =
10×1 cell array
{[ NaN]}
{[ NaN]}
{["Checked"]}
{["Checked"]}
{[ NaN]}
{[ NaN]}
{[ NaN]}
{[ NaN]}
{[ NaN]}
{["Checked"]}
>>
To convert to categorical is relatively straightforward; the NaN
ix=~cellfun(@isstring,LS); % Locate the NaN (isnan fails on string cells so complement)
LS(ix)={"Not Checked"}; % Put another string there--your choice as to what...
categorical(cellstr(LS)) % categorical uses unique() which can't stomach string array input
ans =
10×1 categorical array
Not Checked
Not Checked
Checked
Checked
Not Checked
Not Checked
Not Checked
Not Checked
Not Checked
Checked
>>
Alternatively, the original idea would have been something like
ix=cellfun(@isstring,LS); % this time we really _do_ want the strings
LS(ix)={1}; % turn them to 1s for now to be all numeric array
% This leaves us with
>> LS
LS =
10×1 cell array
{[NaN]}
{[NaN]}
{[ 1]}
{[ 1]}
{[NaN]}
{[NaN]}
{[NaN]}
{[NaN]}
{[NaN]}
{[ 1]}
>>
% convert to categorical, for NaN to be in allowable dataset, define outputs
>> categorical(cell2mat(LS),[nan 1],["UnChecked";"Checked"])
ans =
10×1 categorical array
UnChecked
UnChecked
Checked
Checked
UnChecked
UnChecked
UnChecked
UnChecked
UnChecked
Checked
>>
It's pretty much just your choice which way to proceed...

その他の回答 (1 件)

dpb
dpb 2020 年 6 月 27 日
Use the optional valueset, and perhaps catnames inputs to categorical to define as desired.
  1 件のコメント
Flynn McGuire
Flynn McGuire 2020 年 6 月 28 日
This doesn't seem to work becuase of the NaN's mixed in the column

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeTables についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by