[R] for loop

Petr Savicky savicky at praha1.ff.cuni.cz
Fri May 6 16:43:01 CEST 2011


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.

Thanks to a remark by David, i now see that x[1]^1/7 is meant
as x[1]^(1/7). The following is a solution modified accordingly

  x <- matrix(100, nrow=2, ncol=2)
  x <- x^c(1/7, 1/6)
  rep(x, times=rep(c(7, 6), length=length(x)))

   [1] 1.930698 1.930698 1.930698 1.930698 1.930698 1.930698 1.930698 2.154435
   [9] 2.154435 2.154435 2.154435 2.154435 2.154435 1.930698 1.930698 1.930698
  [17] 1.930698 1.930698 1.930698 1.930698 2.154435 2.154435 2.154435 2.154435
  [25] 2.154435 2.154435

The output is a vector. You require that the output has 6.5 times
more elements than the input, since 10400000/160/10000 = 6.5. This
corresponds to the understanding that odd elements should repeat 7
times and even elements 6 times. However, it is not clear, what
the dimension of the output matrix should be.

Hope this helps.

Petr Savicky.



More information about the R-help mailing list