I am working in R. I have a vector A. It contains values which are integers between 0-10. I want a matrix with 10-X 0s followed by X 1s where X is the corresponding value from vector A.
example:
A = c(1,3,5,8)
becomes
(0,0,0,0,0,0,0,0,0,1
0,0,0,0,0,0,0,1,1,1
0,0,0,0,0,1,1,1,1,1
0,0,1,1,1,1,1,1,1,1)
I know you can use the rep function to replicate values, but it doesn't work on matrices. For example, B=c(rep(0, 10-A), rep(1,A)) doesn't do anything. Is there a quick way of doing this?
Alternative in 2 steps:
N <- 10
B <- matrix(0,nrow=length(A),ncol=N)
B[cbind(rep(seq_along(A),A),N + 1 - sequence(A))] <- 1
B
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
#[1,] 0 0 0 0 0 0 0 0 0 1
#[2,] 0 0 0 0 0 0 0 1 1 1
#[3,] 0 0 0 0 0 1 1 1 1 1
#[4,] 0 0 1 1 1 1 1 1 1 1
I was hoping this would turn out prettier, but it seems to work
N <- 10
A <- c(1,3,5,8)
matrix(
rep(
rep(c(0,1), length(A)),
rbind(N-A, A)
),
byrow=T, ncol=N
)
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,] 0 0 0 0 0 0 0 0 0 1
# [2,] 0 0 0 0 0 0 0 1 1 1
# [3,] 0 0 0 0 0 1 1 1 1 1
# [4,] 0 0 1 1 1 1 1 1 1 1
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