필터 지우기
필터 지우기

Grouping Variables using rowfun Function Rearranging Order to Alphabetical

조회 수: 6 (최근 30일)
How does one keep the original sequencing of variables used for matching in the rowfun?
% Guillaume's Code from Prior Question
data = readtable('ML_Q_3.xlsx', 'ReadVariableNames', false);
%optionally, give better name to the variables of the table
%data.Properties.VariableNames = {'???', '????'}
data = rmmissing(data); %get rid of empty rows
sorted = rowfun(@(v) {v}, data, 'GroupingVariables', 1); %group column 2 by column 1
The resulting sorted names are in alphabetical order (col 1) ['A','B','F','R','X'] .
Where I require it to be per the original ['B','F','R','X','A'] .
I can not find anything in the documentation rowfun how to specify to keep the original order.

채택된 답변

Walter Roberson
Walter Roberson 2019년 7월 24일
unique() with 'stable' option. Take the third output and use it as the grouping for splitapply()
  댓글 수: 8
Walter Roberson
Walter Roberson 2019년 7월 24일
Stephen's elaboration of what I wrote is correct. You need the third of the three possible outputs from unique() in order to use as the grouping variable for splitapply()
Jay
Jay 2019년 7월 25일
data = readtable('ML_Q_2_2.xlsx', 'ReadVariableNames', false);
data = rmmissing(data); %get rid of empty rows
[~,~,X] = unique(data,'stable')
output = splitapply(@sum,data, X) % Error returned
Error returned for "output":
Group numbers must be a vector of positive integers, and cannot be a sparse vector.
Also, "X" is returning a vector based on the values in the second column and not the key variables of the first column (data):
I.E.
[1 2 3 4 5 1 6 7 8 9 1 10 11 12 13 1 14 15 16 1 17 18 19 1 20 21 22 ].
Not [1 2 3 4 5].
I resolved this by specifying the first column
[~,~,X] = unique(data(:,1),'stable')
I then used the following code to sum the values of the second column to their correlating key variables.
grouped = splitapply(@sum,data(:,2), X)
Thank you for pointing me in the right direction Walter.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by