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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With