Adding a categorical column to a Table

25 ビュー (過去 30 日間)
Amanda
Amanda 2020 年 4 月 21 日
コメント済み: Peter Perkins 2020 年 4 月 27 日
Dear All,
I've been stucked with a fairly simple problem for a couple of hours now. I'd like to know how to add a new categorical column to a table in which:
1) from cell 1 to 68 I want to add a string value called 'v';
2) from 69 to 100 I want to add a string value called 'a';
3) from 101 to 155 I want to add a string value called 'i'
Is there an easy way to write that? cause I could do it manually, but I'd like to know the right way to do it when working with tables (or arrays also).
This is what I was trying to do:
>> tabPC = table(PC1, PC2, PC3); %this is a 155x3 table
>> tabPC.Var4{1,1} = 'v';
>> tabPC.Var4{69} = 'a';
>> tabPC.Var4{101} = 'i';
>> tabPC.Properties.VariableNames{4} = 'mycategories';
>> tabPC.mycategories = categorical(tabPC.mycategories)
This code just added a new 4th column to the original table (named 'mycategories' ) with 'v', 'a' and 'i' strings into the 1th, 69th and 101th cell positions respectively. But these values don't repeat in each cell. E.g I would like the 'v' value to show from cell 1 to cell 68, but it appears only in the first cell. As well as for the other values.
Thanks in advance for your precious help!

採用された回答

Sindar
Sindar 2020 年 4 月 22 日
編集済み: Sindar 2020 年 4 月 22 日
In one line:
mytable.mycategories = categorical(repelem({'v';'a';'i'},[68,32,55]));
To explain:
Matlab will add a column if you define a new variable. This saves you renaming it.
repelem takes your collection of possible categories and repeats each element according to the vector in the 2nd input (so, 68 'v's, 32 'a's, 55 'i's)
Note: swapping the order of converting to categorical and repeating elements may be faster; I don't know:
mytable.mycategories = repelem(categorical({'v';'a';'i'}),[68,32,55]);
  2 件のコメント
Amanda
Amanda 2020 年 4 月 22 日
Thank you for the fast reply! That solved my issue.
Peter Perkins
Peter Perkins 2020 年 4 月 27 日
In this case it doesn't make much difference, but Sindar is right: for cases with large amounts of data, putting the repelem outside the categorical construction would be better, memorywise.

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

その他の回答 (0 件)

カテゴリ

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

タグ

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by