Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sapply (from R) equivalent for Julia?

Tags:

julia

Suppose I have an 2 dimensional array and I want to apply several functions to each of its columns. Ideally I would like to get the results back in the form of a matrix (with one row per function, and one column per input column).

The following code generates the values I want, but as an Array of Arrays.

A = rand(10,10)
[mapslices(f, A, 1)  for f in [mean median iqr]]

Another similar example is here [Julia: use of pmap with matrices

Is there a better syntax for getting the results back in the form of a 2 dimensional array, instead of an array of arrays?

What I'd really like is something with a functionality similar to sapply from R. [https://stat.ethz.ch/R-manual/R-devel/library/base/html/lapply.html]

like image 619
Rob Donnelly Avatar asked May 16 '15 22:05

Rob Donnelly


2 Answers

You can use an anonymous function as in

mapslices(t -> [mean(t), median(t), iqr(t)], A, 1)

but using comprehensions and splatting, as in your last example, is also fine. For very large arrays, you might want to avoid the temporary allocations introduced by transpose and splatting, but in most cases you don't have to pay attention to that.

like image 84
Andreas Noack Avatar answered Oct 29 '22 06:10

Andreas Noack


After playing around a bit I found one option, but I am still interested in hearing if there are any better ways of doing it.

[[mapslices(f, A, 1)'  for f in [mean median iqr]]...]
like image 40
Rob Donnelly Avatar answered Oct 29 '22 07:10

Rob Donnelly