Rehsaping Data Table to new format

1 visualizzazione (ultimi 30 giorni)
Matt
Matt il 7 Apr 2017
Risposto: Matt il 10 Apr 2017
Hi, I have a data table that exists like:
[date] [field] [data]
1/1/2017 A 1
1/2/2017 A 2
1/3/2017 A 3
1/1/2017 B 3
1/2/2017 B 2
1/3/2017 B 1
1/1/2017 C 4
1/2/2017 C 5
1/3/2017 C 6
and i want to reshape the data to be like this:
[Date] [A] [B] [C]
1/1/2017 1 3 4
1/2/2017 2 2 5
1/3/2017 3 1 6
so that each unique value in fields becomes a new field name in the new table.
I saw this conversion done in a tutorial the other day, but cant recall how it was done at all, thanks for any input in advance!
Matt

Risposta accettata

Peter Perkins
Peter Perkins il 7 Apr 2017
I think you are looking for unstack:
>> t = cell2table( ...
{'1/1/2017', 'A', 1; ...
'1/2/2017', 'A', 2; ...
'1/3/2017', 'A', 3; ...
'1/1/2017', 'B', 3; ...
'1/2/2017', 'B', 2; ...
'1/3/2017', 'B', 1; ...
'1/1/2017', 'C', 4; ...
'1/2/2017', 'C', 5; ...
'1/3/2017', 'C', 6},'VariableNames',{'date' 'field' 'data'});
>> t.date = datetime(t.date,'InputFormat','MM/dd/yyy');
>> t.field = categorical(t.field)
t =
9×3 table
date field data
___________ _____ ____
01-Jan-2017 A 1
02-Jan-2017 A 2
03-Jan-2017 A 3
01-Jan-2017 B 3
02-Jan-2017 B 2
03-Jan-2017 B 1
01-Jan-2017 C 4
02-Jan-2017 C 5
03-Jan-2017 C 6
>> t2 = unstack(t,'data','field')
t2 =
3×4 table
date A B C
___________ _ _ _
01-Jan-2017 1 3 4
02-Jan-2017 2 2 5
03-Jan-2017 3 1 6

Più risposte (2)

Steven Lord
Steven Lord il 7 Apr 2017
If your data is stored in a table or timetable, use unstack. The first example on that documentation page is pretty close to the exact scenario you gave, so it should be easy to adapt for your needs.

Matt
Matt il 10 Apr 2017
Both answer the question and accomplish what i was looking to do, thanks very much!

Categorie

Scopri di più su Tables in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by