How can I merge rows into one with the same ID number?

6 次查看(过去 30 天)
I have a spreadsheet with patient IDs and diagnoses; all diagnoses are in their own column and I want to merge the rows based on patient ID to make one row and keep all the data. I'm not sure how to go about doing this?
Example of table:
PT Dx1 Dx2 Dx3
A 1 0 0
A 0 1 0
A 0 0 1
I want:
PT Dx1 Dx2 Dx3
A 1 1 1

回答(1 个)

Stephen23
Stephen23 2020-9-21
编辑:Stephen23 2020-9-22
Assuming that the non-diagonal values are exactly zero, then you could use varfun something like this:
>> T = cell2table({'A',1,0,0;'A',0,2,0;'A',0,0,3;'B',4,0,0;'B',0,5,0;'B',0,0,6})
T =
Var1 Var2 Var3 Var4
____ ____ ____ ____
'A' 1 0 0
'A' 0 2 0
'A' 0 0 3
'B' 4 0 0
'B' 0 5 0
'B' 0 0 6
>> U = varfun(@sum,T,'GroupingVariables','Var1')
U =
Var1 GroupCount sum_Var2 sum_Var3 sum_Var4
____ __________ ________ ________ ________
A 'A' 3 1 2 3
B 'B' 3 4 5 6
Of course you can rename/remove those table variables as required.

类别

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