Creating a matrix in R from a vector

I work in R. I have a vector A. It contains values ​​that are integers from 0 to 10. I want a matrix with 10-X 0 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 with matrices. For example, B=c(rep(0, 10-A), rep(1,A))

it does nothing. Is there a quick way to do this?

+3


source to share


2 answers


I was hoping it would get 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

      

+3


source


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

      

+5


source







All Articles