[R] Avoiding FOR loops

From: dxc13 <dxc13_at_health.state.ny.us>
Date: Sun, 6 Jan 2008 16:55:31 -0800 (PST)

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:

> x

     [,1] [,2] [,3]

[1,]    4   11    1
[2,]    1    9    2
[3,]    7    3    3
[4,]    3    6    4
[5,]    6    8    5


> xk
Var1 Var2 Var3 1 -0.25 1.75 0.5 2 0.75 1.75 0.5 3 1.75 1.75 0.5 4 2.75 1.75 0.5 5 3.75 1.75 0.5 6 4.75 1.75 0.5 7 5.75 1.75 0.5 8 6.75 1.75 0.5

9 7.75 1.75 0.5
10 -0.25 2.75 0.5

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

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

-- 
View this message in context: http://www.nabble.com/Avoiding-FOR-loops-tp14656517p14656517.html
Sent from the R help mailing list archive at Nabble.com.

______________________________________________
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 - 00:58:58 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 - 01:30:06 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