Re: [R] Outer, kronecker, etc.

From: Prof Brian Ripley <ripley_at_stats.ox.ac.uk>
Date: Wed, 12 Nov 2008 18:10:55 +0000 (GMT)

See ?Vectorize.

sqrt() works on a matrix, and so does

A <- matrix(1:4^2,2,2)
A[] <- sapply(A, sqrt)

On Wed, 12 Nov 2008, Stavros Macrakis wrote:

> `outer` (and related functions like kronecker) require that their
> functional argument operate elementwise on arrays. This means for
> example that
>
> outer( 1:2, 3:4, list)
>
> or
>
> outer(1:2,3:4,function(a,b){1})
>
> gives an error.
>
> Is there a version of `outer`/`kronecker`/etc. that takes arbitrary
> functions and does its own elementwise mapping? In the first example
> above, I'd expect the result to be the same as
>
> mm <- matrix(list(list(1,3),list(1,4),list(2,3),list(2,4)),2,2)
>
> which prints as
>
> [,1] [,2]
> [1,] List,2 List,2
> [2,] List,2 List,2
>
> By the way: how can I get this not to abbeviate the entries but
> instead give me something like:
>
> [,1] [,2]
> [1,] list(1, 3) list(2, 3)
> [2,] list(1, 4) list(2, 4)

Write your own print function. It does not 'abbeviate the entries': it prints a summary of them.

mm[] <- sapply(mm, deparse)

> By-the-way^2: is there some Xapply function that maps a function over
> all the elements of a structure (vector, matrix, list, ...) and
> preserves the original structure? For example, I'd want
> Xapply(matrix(1:4^2,2,2),sqrt) == sqrt(matrix(1:4^2,2,2)). In this
> case, I'd use Xapply(as.character,mm), because as.character returns a
> vector.
>
> Thanks,
>
> -s
>
> ______________________________________________
> R-help_at_r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> and provide commented, minimal, self-contained, reproducible code.
>

```--
Brian D. Ripley,                  ripley_at_stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help