Adding a new variable called 'Count', which Indexes or counts the occurrence of each stock_code based on their dates
Afficher commentaires plus anciens
Hi All, I need some guidance on adding incremental Count value to each stock_codes. I have a table with variables, Stock_code, date, close, low, high columns. I need help on, For example., Stocks: 200 Stocks totally, No.of Years: 1year(270 days, if we neglect holidays and suspension period etc.,). 1stock would have had 270 days, next stock might be having 200 days, 3rd like 230 days etc., So i need to add a variable called count, and it should have values like 1,2,3,4,5...270 for stock1, Repeat for Stock2 like 1,2,3,4,5...200, Stock3 like 1,2,3,4,5...230. Kindly advise how to achieve this.
5 commentaires
Joshua
le 27 Mar 2017
Do you have any code written? What are you trying to do with the variable "count"? Is it going to be a column vector of numbers (say from 1 to 270) that will be displayed as a column of the table? If so you could try:
count=[1:270]'
And then add count into the table as another column.
Lakshmi Gandhi
le 27 Mar 2017
Andrei Bobrov
le 27 Mar 2017
Please attach small example your data here
Lakshmi Gandhi
le 27 Mar 2017
Lakshmi Gandhi
le 27 Mar 2017
Réponse acceptée
Plus de réponses (1)
Peter Perkins
le 27 Mar 2017
If you are using R2016b or later, you are almost certainly better off using a timetable, since those already have methods for lagging, synchronizing, aggregating, and so on. Prior to 16b, use varfun with 'GroupingVariables'. Andrei's code would be a one-liner. Since all you're doing here is assigning a monotonic index withing each group, using varfun seems a little like overkill, but I suspect once you do something more complicated, you'll appreciate it's power.
>> t = table({'a';'a';;'b';'b';'b'},datetime(2017,3,[21;22;22;23;24]),randn(5,1),'VariableNames',{'Symbol','Date','X'})
t =
5×3 table
Symbol Date X
______ ___________ ________
'a' 21-Mar-2017 0.32519
'a' 22-Mar-2017 -0.75493
'b' 22-Mar-2017 1.3703
'b' 23-Mar-2017 -1.7115
'b' 24-Mar-2017 -0.10224
>> tCount = varfun(@(x)(1:length(x))', t, 'GroupingVariables','Symbol','InputVariables','X');
>> t.Count = tCount.Fun_X
t =
5×4 table
Symbol Date X Count
______ ___________ ________ _____
'a' 21-Mar-2017 0.32519 1
'a' 22-Mar-2017 -0.75493 2
'b' 22-Mar-2017 1.3703 1
'b' 23-Mar-2017 -1.7115 2
'b' 24-Mar-2017 -0.10224 3
Catégories
En savoir plus sur Dates and Time dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
