8
$\begingroup$

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}}
$\endgroup$
1

2 Answers 2

10
$\begingroup$

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} *)
$\endgroup$
16
$\begingroup$

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}]}
$\endgroup$
1
  • $\begingroup$ 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... $\endgroup$
    – user4860
    Dec 2, 2012 at 18:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.