Re: [R] Avoiding FOR loops

From: Charilaos Skiadas <cskiadas_at_gmail.com>
Date: Sun, 6 Jan 2008 20:18:20 -0500

On Jan 6, 2008, at 7:55 PM, dxc13 wrote:

>
> useR's,
>
> I would like to know if there is a way to avoid using FOR loops to
> perform
> the below calculation.
>
> Consider the following data:
>
snip
> Here, X is a matrix of 3 variables in which each is of size 5 and
> XK are
> some values that correspond to each variable. For each variable, I
> want to
> do:
>
> |Xi - xkj| where i = 1 to 3 and j = 1 to 10
>
That should be i=1 to 5 I take it?

If I understand what you want to do, then the outer function is the key:

lapply(1:3, function(i) { outer(x[,i], xk[,i], "-") } )

This should land you with a list of three 5x10 tables

> It looks as if a double FOR loop would work, but can the apply
> function
> work? Or some other function that is shorter than a FOR loop?
> Thank you, I
> hope this makes sense.
>
> Derek
>

Haris Skiadas
Department of Mathematics and Computer Science Hanover College



R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Mon 07 Jan 2008 - 01:22:24 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 07 Jan 2008 - 02:30:05 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive