1

I would like to combine two matrices with different row count:

k<-c(11,21,31,4,5,6,7,8,9)
k<-as.matrix(k)
m<-c(10,20,30,4,5,6)
m<-as.matrix(m)

I am using this command but doesnt work correctly for me:

j<-merge(m,k,all=TRUE)

what should I do to do this job

EDIT

I would like to have something like this:

   [,1]  [,2]
[1,] 11    10
[2,] 21    20 
[3,] 31    30
[4,] 4     4
[5,] 5     5
[6,] 6     6
[7,] 7     NA
[8,] 8     NA
[9,] 9     NA
Cœur
  • 37,241
  • 25
  • 195
  • 267
Kaja
  • 2,962
  • 18
  • 63
  • 99
  • Please be more specific as to how exactly you would like to combine the matrices. Are you simply looking for `rbind()`, assuming that the numbers of *columns* are identical? – Stephan Kolassa Mar 26 '14 at 09:45
  • I would like to `cbind` but I get an error: number of rows of matrices must match (see arg 2) – Kaja Mar 26 '14 at 09:47
  • What result do you expect from `cbind()`, taking into account that, indeed, the number of rows is unequal? `cbind(1:9,1:6)` may be what you are looking for, which recycles the shorter vector and gives a warning. I suggest thinking about *why* you would want to `cbind` vectors of unequal length. – Stephan Kolassa Mar 26 '14 at 09:50

3 Answers3

3

Assuming you would like to merge m and k colwise...

library(zoo)

my_k <- zoo(k)
my_m <- zoo(m)

j <- as.matrix(merge(my_m, my_k))
Miha Trošt
  • 2,002
  • 22
  • 25
  • thank you :) how can I do the same thing for `rbind` with different column count? – Kaja Mar 26 '14 at 12:29
  • 1
    @Kaja Take a look at library(plyr) and the function rbind.fill.matrix(). It might be usefull. – Miha Trošt Mar 26 '14 at 12:45
  • It needs RCpp, and Rcpp needs R (≥ 3.0.0) and I cant upgrade my R.Is there another way to do this job? – Kaja Mar 26 '14 at 12:48
  • there is another way [here](http://stackoverflow.com/questions/18003717/is-there-any-efficient-way-than-rbind-filllist) and anather [here](http://stackoverflow.com/questions/17308551/do-callrbind-list-for-uneven-number-of-column?lq=1) – Miha Trošt Mar 26 '14 at 12:57
2

If there are only two vectors, probably simplest to make them both the same length

mlen <- max(length(m), length(k))
length(m) <- length(k) <- mlen
cbind(m,k)

will give the required result.

Gavin Kelly
  • 2,374
  • 1
  • 10
  • 13
1

Another way

k <- as.data.frame(matrix(c(1:9, 11,21,31,4,5,6,7,8,9), 9,2))
m <- as.data.frame(matrix(c(1:6, 10,20,30,4,5,6), 6, 2))
j <- as.matrix(merge(k,m, by = "V1", all.x = T)[, -1])
David Arenburg
  • 91,361
  • 17
  • 137
  • 196