3

In a iterative algorithm, I identify at each step one, several or no row(s) to be taken into account for further calculation. To store the row(s) of interest, I must bind two variables: X.id and X.val. I currently use :

cbind(X.id,X.val)

It works fine when X.id and X.val are both matrices:

X.id  <- matrix(1,nrow=2,3)
X.val <- matrix(1,nrow=2,1)     
 cbind(X.id,X.val)
     [,1] [,2] [,3] [,4]
[1,]    1    1    1    1
[2,]    1    1    1    1

but not when they have one row:

X.id  <-  c(1,1,1)
X.val <- matrix(1,nrow=1,1)
cbind(X.id,X.val)

Which gives the following error:

 In cbind(c(1, 1, 1), matrix(1, nrow = 1, 1)) : number of rows of result is not a multiple of vector length (arg 1)

The proposed solution should work when the number of row(s) is(are) 0,1 and n while conserving the dimension of the matrices!

WAF
  • 1,141
  • 20
  • 44
  • use `rbind` to bind rows – dickoa Apr 24 '13 at 15:33
  • 1
    You might also be looking for [cbind.fill](http://stackoverflow.com/q/7962267/324364). – joran Apr 24 '13 at 15:34
  • 3
    I would suggest to use a list instead of a matrix to store your values. Something like `x=list()` and then iteratively `x[[length(x)+1]]=your_vector`. – cryo111 Apr 24 '13 at 15:40
  • 1
    Do note that iteratively building an object can become really, really, really slow if the number of elements in the objects becomes big. Preallocating a result object big enough circumvents this problem. – Paul Hiemstra Apr 25 '13 at 07:38
  • BTW: In your second example, `c(1,1,1)` is NOT a matrix but a vector. Try `cbind(matrix(c(1,1,1),ncol=3,nrow=1),X.val)` and it works... And if your final matrix gets really large, please note Paul's important comment above. – cryo111 Apr 25 '13 at 12:09

2 Answers2

5

I believe you are looking for append(X.id,X.val)

Maxim.K
  • 4,120
  • 1
  • 26
  • 43
  • Append works fine if X.id and X.val have one row but if they have more than one it gives a vector and not a matrix – WAF Apr 25 '13 at 07:11
  • @FWaldner you might want to make your question more clear then, providing an example that fails. Append worked in the example you provided, and afaik passed the conditions you initially formulated. – Maxim.K Apr 25 '13 at 07:49
0

The question is a little unclear with regards to the relationship between id and value. It is likely that the solution you seek is to use a list as @cyro111 describes in the comments.

Using cbind is not going to give you the results you seek, since it will coerce X.id into a column. (Unless of course, that is what you are after. Again, it is a bit unclear from your question).

You can also simply use c() as in

 > c(X.id, X.val)
 [1] 1 1 1 1
Ricardo Saporta
  • 54,400
  • 17
  • 144
  • 178
  • @FWaldner, as Maxim.K pointed out, your question is horribly unclear. If you expect X.id to be multidimensional, that should be evident in your question. – Ricardo Saporta Apr 25 '13 at 14:43