Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge vectors with different length into a matrix one after the other

Tags:

r

vector

matrix

Let's assume that we have the following three vectors.

L = c("1", "3")
K = c("2", "9", "2:9")
S = c("7")

Is there any way to combine them into a matrix that will look like the above ?

L    K    S
1    0    0
3    0    0
0    2    0
0    9    0
0    2:9  0
0    0    7

Thank you.

like image 747
J. Doe Avatar asked Mar 09 '23 16:03

J. Doe


1 Answers

Here's another way to do it: you first create a matrix of 0s, and then using two vectors of indexes k and 1:l, you input your values into it at the right locations.

l = length(c(L,K,S))
k = rep(1:3,times=c(length(L),length(K),length(S)))
m = matrix(0,ncol=3,nrow=l)
m[cbind(1:l,k)] = c(L,K,S)
     [,1] [,2]  [,3]
[1,] "1"  "0"   "0" 
[2,] "3"  "0"   "0" 
[3,] "0"  "2"   "0" 
[4,] "0"  "9"   "0" 
[5,] "0"  "2:9" "0" 
[6,] "0"  "0"   "7" 

Edit: For a version that generalizes better to a larger number of input vectors, as per @DavidArenburg's comment, you could do:

l = list(L,K,S)
len = length(unlist(l))
k = rep(seq_along(l), lengths(l))
m = matrix(0, nrow=len, ncol=length(l))
m[cbind(1:len, k)] = unlist(l)
like image 103
Lamia Avatar answered Mar 29 '23 01:03

Lamia