Group, sum and weighted average in f# -


i have following data:

let data = [(41609.00 , 10000., 3.822); (41609.00, 60000., 3.857); (41974.00 , 20000., 4.723 ); (41974.00, 30000., 3.22 ); (41974.00 , 4000., 4.655 ); (42339.00, 7000., 4.22 ); (42339.00 , 5000., 3.33)] 

fist column = oadate, 2nd = volume, third = price.

i want group date, sum volume , compute weighted average price. have far:

let aggr data =      data     //multiply second , third column element element     |> seq.map (fun (a, b, c) -> (a, b, b * c))     //group first column     |> seq.groupby fst     //sum column 2 & 3 based on group of column 1     |> seq.map (fun (d, e, f) -> (d, e |> seq.sum, f |> seq.sum))      //take sum , grouped column 1 & 2 , compute weighted average of third     |> seq.map (fun (g, h, i) -> (g, h, i/h))  

i m getting type mismatch tuples have differing lengths. have used similar syntax before without issues. please point me in right direction?

update:

in case interested solution is: tomas , leaf

let aggr data =  data |> seq.map (fun (a, b, c) -> (a, b, b * c)) |> seq.groupby (fun (a, b, c) -> a) |> seq.map (fun (key, group) -> group |> seq.reduce (fun (a, b, c) (x, y, z) -> a, b+y , c+z)) |> seq.map (fun (g, h, i) -> (g, h, i/h))  

the first problem in code calling seq.groupby fst argument. not work because fst function returns first element of two-element tuple, input three-element tuple. sadly, function not work any tuple. need write lambda selects first value out of three:

(...) |> seq.groupby (fun (a, b, c) -> a) 

the next problem mapping in next step. grouping produces list of tuples containing key (time) first element , group containing list of elements original input sequence (three-element tuples in case). return key sum of second component in group, can write:

(...) |> seq.map (fun (key, group) -> key, group |> seq.sumby (fun (_, v, _) -> v)) 

i'm not entirely sure want second , third columns, should give idea how continue.


Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

c++ - Correct method for redrawing a layered window -

java.util.scanner - How to read and add only numbers to array from a text file -