필터 지우기
필터 지우기

Merging two categorical columns using a rule

조회 수: 1 (최근 30일)
Wendy Cameron
Wendy Cameron 2018년 5월 11일
댓글: Wendy Cameron 2018년 5월 12일
Hi,
I am wanting to merge/add 2 categorical columns but need to use a rule.
For example a= [Flowering not not not], b=[not not not budburst] and I want the final output to be c=[Flowering not not Budburst]?
Basically, when merging/adding the two vectors, I want the word "flowering" or "budburst" to take precedence over "not". "Flowering" will never clash with "budburst" and "not "not" would give a "not".
Thanks, Wendy

채택된 답변

Ameer Hamza
Ameer Hamza 2018년 5월 11일
편집: Ameer Hamza 2018년 5월 11일
Here is one way
% Extracting data from yor file
data = readtable('phenology.xls');
a = categorical(data.A);
b = categorical(data.B);
% preparing default output vector
c = categorical(repmat({'not'}, size(a)));
indA = ~ismember(a, 'not');
indB = ~ismember(b, 'not');
c(indA) = a(indA);
c(indB) = b(indB);
isequal(c, data.C)
ans =
1 <--- The generated c is same as in your xls file.

추가 답변 (3개)

Greg
Greg 2018년 5월 11일
Make your categorical array ordinal (with "not" as the lowest value), then use c = max(a,b). This is only guaranteed to work since you said valid values won't conflict.
  댓글 수: 3
Greg
Greg 2018년 5월 12일
Have a read of the documentation page " Ordinal Categorical Arrays ."
Basically, you specify the valueset (allowable entries) in order of smallest to largest:
valueset = {'not';'Budburst';'Flowering'};
var = categorical(a,valueset,'ordinal');
Wendy Cameron
Wendy Cameron 2018년 5월 12일
Thank you, I've read that now and it seems to make even more sense the way you've written it here!.
Thank you very much. Wendy

댓글을 달려면 로그인하십시오.


Wendy Cameron
Wendy Cameron 2018년 5월 11일
Hi,
I have attached some sample data. Basically I have columns A and B but want to get column C. I couldn't quite get the method above to work but I am very new to Matlab.
Thanks for your patience. Wendy
  댓글 수: 1
Ameer Hamza
Ameer Hamza 2018년 5월 11일
I just tested my code with your data and it is giving correct output. Can you tell which line is creating the error? Refer to my edited answer to see how to read data from the xls file.

댓글을 달려면 로그인하십시오.


Wendy Cameron
Wendy Cameron 2018년 5월 11일
Yes that worked with the table I sent you as you describe. I get a 42 x 1 categorical - thank you very much. I'm now just trying to join that column into my original table. Join or interjoin might work.
Thanks, Wendy
  댓글 수: 3
Wendy Cameron
Wendy Cameron 2018년 5월 11일
Brilliant, thank you - that works perfectly. I've learnt a lot thank you.
Very much appreciated.
Ameer Hamza
Ameer Hamza 2018년 5월 11일
You are welcome.

댓글을 달려면 로그인하십시오.

카테고리

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