Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a matrix in R from a vector

Tags:

r

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?

like image 667
Phil Avatar asked Jan 18 '26 02:01

Phil


2 Answers

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
like image 102
thelatemail Avatar answered Jan 19 '26 19:01

thelatemail


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
like image 35
MrFlick Avatar answered Jan 19 '26 18:01

MrFlick