8

I have a $N \times M$ list of lists, or rather, a list of records and I want to map a function over its columns (e.g. find the mean temperature, age, etc.). Map would apply the function to each list within the list, but I want to slice vertically, rather than horizontally. How can I do this?

Example: Return a list of means for {{1, 4, 7}, {2, 5, 8}, { 3, 6, 9}} rather than {1,2,3}, etc.

The list:

{{1, 2, 3}, 
 {4, 5, 6},
 {7, 8, 9}}
Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263

2 Answers2

16

For Mean you don't have to do any transformation to the input array

 data = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
 Mean[data]
 (* {4, 5, 6} *)

because (from docs Mean >> More Information)

enter image description here

that is, Mean "threads" over its input when it is fed an array.

In general, in addition to

func/@Transpose[data] 

(as in @m_goldberg's answer)

you can also use

MapThread[func, data]

or

func /@ Thread[data]

to get

{func[{1, 4, 7}], func[{2, 5, 8}], func[{3, 6, 9}]}
kglr
  • 394,356
  • 18
  • 477
  • 896
  • Transpose is what I was looking for in the end. It let me map my KDE over my columns of data nicely.

    Thank you very much kguler and m_goldberg!

    Now I'm off to read up on memory usage...

    –  Dec 02 '12 at 18:20
10

Transpose followed by mapping Mean over the array should do the job.

data = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
Mean /@ Transpose[data]
(* ==> {4, 5, 6} *)
m_goldberg
  • 107,779
  • 16
  • 103
  • 257