2

I would like to ask, how to set a value in array using looping. say like this

a<-3
b<-4
for( i in 1:5)
{
  x[i] <- cbind(a*i, b*i)
}

but i always get error saying : In x[i] <- cbind(a * i, b * i) : number of items to replace is not a multiple of replacement length. I used "paste" but seems it's not the solution. What is the problem ? If it were solved, can I get the value by using ; for example x[2][,2] to get the value of b * 2 ? thank you

Elbert
  • 516
  • 1
  • 5
  • 15
  • You shouldn't use for loops in R to grow an array. Try to do `x = a * c(1:5)` instead. I'm not sure what exactly you're doing in your code. – TheComeOnMan Apr 18 '16 at 11:04

2 Answers2

3

You can do it this way :

a <- 3
b <- 4
i <- 1:5
x <- cbind(a*i, b*i)
0

Make use of the matrix functions and the fact that R computes directly on vectors and matrices.

In your case, try this:

outer(1:5, 3:4, FUN = "*")

     [,1] [,2]
[1,]    3    4
[2,]    6    8
[3,]    9   12
[4,]   12   16
[5,]   15   20
Andrie
  • 176,377
  • 47
  • 447
  • 496