[R] ugly loop

Marc Schwartz MSchwartz at MedAnalytics.com
Fri Apr 22 15:17:54 CEST 2005


On Fri, 2005-04-22 at 08:58 -0400, Bill Simpson wrote:
> The following code is slow and ugly:
> 
> count<-0
> for(i in 1:nrow(ver))
>   for(j in 1:ncol(ver))
>     {
>     count<-count+1
>     x[count]<-pt$x[ver[i,j]]
>     y[count]<-pt$y[ver[i,j]]
>     z[count]<-pt$z[ver[i,j]]
>     }
> 
> Please help me make it better.
> 
> Thanks!

The following should work:

> ver <- matrix(sample(1:16, 16), ncol = 4)
> pt <- data.frame(x = sample(1:16, 16), 
+                  y = sample(1:16, 16),
+                  z = sample(1:16, 16))
 
> ver
     [,1] [,2] [,3] [,4]
[1,]    8    9    5   13
[2,]   14   16    1   10
[3,]   12    2   11    7
[4,]    6    3    4   15
> pt
    x  y  z
1   6 15 15
2   9  2  3
3  11  1  5
4  14  4 10
5  13  7 14
6   1 14  7
7  15 10  4
8  10  5 12
9   4 12  2
10  8  8 13
11 16 11  1
12  7 13  9
13  2 16 11
14  3  9 16
15  5  6  8
16 12  3  6

> x <- pt$x[ver]
> y <- pt$y[ver]
> z <- pt$z[ver]
 
> x
 [1] 10  3  7  1  4 12  9 11 13  6 16 14  2  8 15  5
> y
 [1]  5  9 13 14 12  3  2  1  7 15 11  4 16  8 10  6
> z
 [1] 12 16  9  7  2  6  3  5 14 15  1 10 11 13  4  8


Keep in mind that a matrix is a vector with dims, so you can fill a
vector from the matrix simply by doing the indexing with a single value,
which will do the fill indexed column by column.

HTH,

Marc Schwartz




More information about the R-help mailing list