[R] for loop

David Winsemius dwinsemius at comcast.net
Fri May 6 15:49:55 CEST 2011


On May 6, 2011, at 4:24 AM, Petr Savicky wrote:

> On Fri, May 06, 2011 at 02:28:57PM +1000, andre bedon wrote:
>>
>> Hi,
>> I'm hoping someone can offer some advice:I have a matrix "x" of  
>> dimensions 160 by 10000. I need to create a matrix "y", where the  
>> first 7 elements are equal to x[1]^1/7, then the next 6 equal to  
>> x[2]^1/6, next seven x[3]^1/7 and so on all the way to the  
>> 10400000th element. I have implemented this with a for loop an hour  
>> ago and it is still loading, can anyone offer any suggestions as to  
>> how I can create this matrix without using loops? I would really  
>> appreciate any suggestions.
>
> Hi.
>
> Since indexing x[1], x[2], ... is used and also the description
> of y corresponds more to a vector, let me first suggest a solution
> for vectors.
>
>  x <- rep(42, times=4) # any vector of even length
>  x <- x/c(7, 6)
>  rep(x, times=rep(c(7, 6), length=length(x)))
>  [1] 6 6 6 6 6 6 6 7 7 7 7 7 7 6 6 6 6 6 6 6 7 7 7 7 7 7
>
> The input vector may be obtained using c() from a matrix. The
> output vector may be reformatted using matrix(). However, for
> a matrix solution, a more precise description of the question
> is needed.

I certainly agree there, but you have pointed the way to a possible  
solution if the OP wants a solution that works along column-wise  
application of the 7 alternate with 6 rule applied to a smaller  
version that might be called "minimal":

mtx <- matrix(1:160, 16, 10)
mtx^(1/c(7,7,7,7,7,7,7,6,6,6,6,6,6) )  # argument recycling results in  
alternating lengths of 7 and 6

(takes less than 5 seconds, and you should expect a warning message  
since 160*10000 is not evenly divisible by 13.)

I am not smart enough to know whether mtx2[160,10000] should be  
1600000^(1/6) or (.)^(1/7) but this suggests it is (1/6):
 > all.equal( mtx2[160,10000] , 1600000^(1/7) )
[1] "Mean relative difference: 0.2883231"
 > all.equal( mtx2[160,10000] , 1600000^(1/6) )
[1] TRUE

If he wanted it to be row-wise then he could transpose, operate, and  
back-transpose. This, of course, assumes that the OP did not really  
mean x[1]^1/7 but rather meant x[1]^(1/7), since I know of no computer  
language where exponentiation is lower in precedence than division.

>
> Hope this helps.
>
> Petr Savicky.
-- 
David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list