# [R] matrix values linked to vector index

arun smartpink111 at yahoo.com
Sun Oct 13 16:22:25 CEST 2013

```Also:
mat+0
#or

mat*1

#However, sapply() based solutions would be slower in large matrices.

#Speed
makeMat3 <- function(x,n){
if(is.numeric(x)){
x <- as.integer(round(x))
x}
stopifnot(is.integer(x))
if(length(x)>=n & max(x)<=n){
indx<-rep(rep(c(1,0),max(length(x),n)),rbind(x,n-x))

m1<-  matrix(indx,nc=n,byr=TRUE)
}

else if(length(x) < n) {
indx<-rep(rep(c(1,0),n),c(as.vector(rbind(x,n-x)),rep(c(0,n),n-length(x))))
m1<-matrix(indx[seq_len(length(indx)-(n*(n-length(x))))],nc=n,byr=TRUE)
}
else print(paste("Not possible: Number of columns less than the maximum value of ", max(x), "or length of vector"))
m1
}

set.seed(124)
xtest<- sample(0:9,1e7,replace=TRUE)
system.time(res3<- makeMat3(xtest,9))
#   user  system elapsed
# 2.000   0.528   2.533
system.time({res4<- t(sapply(xtest,">=",1:max(xtest)))
res4<- res4*1})
#   user  system elapsed
# 42.648   0.728  43.461
identical(res3,res4)
#[1] TRUE

A.K.

On Sunday, October 13, 2013 3:55 AM, Christoph Häni <ch.haeni at gmail.com> wrote:
Just a further suggestion:

vec <- c(3,2,5,0,1)

mat <- t(sapply(vec,">=",1:max(vec)))

ifelse(mat,1,0)

Cheers,
Christoph

2013/10/11 arun <smartpink111 at yahoo.com>:
> Hi,
>
> In the example you showed:
>
> m1<- matrix(0,length(vec),max(vec))
> 1*!upper.tri(m1)
>
> #or
>  m1[!upper.tri(m1)] <-  rep(rep(1,length(vec)),vec)
>
> #But, in a case like below, perhaps:
> vec1<- c(3,4,5)
>
>  m2<- matrix(0,length(vec1),max(vec1))
>  indx <- cbind(rep(seq_along(vec1),vec1),unlist(tapply(vec1,list(vec1),FUN=seq),use.names=FALSE))
> m2[indx]<- 1
>  m2
> #     [,1] [,2] [,3] [,4] [,5]
> #[1,]    1    1    1    0    0
> #[2,]    1    1    1    1    0
> #[3,]    1    1    1    1    1
>
>
>
>
> A.K.
>
>
> Hi-
>
> I'd like to create a matrix of 0's and 1's where the number of
> 1's in each row defined by the value indexed in another vector, and
> where the (value-1) is back-filled by 0's.
>
> For example, given the following vector:
> vec= c(1,2,3)
>
> I'd like to produce a matrix with dimensions (length(vec), max(vec)):
>
> 1,0,0
> 1,1,0
> 1,1,1
>
> Thank you!
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help