I have a fun challenge: I'm trying to construct a a binary matrix from an integer vector. The binary matrix should contain as many rows as the length of vector, and as many columns as the max value in the integer vector. The ith row in the matrix will correspond to the ith element of the vector, with the row containing a 1 at the position j, where j is equal to the value of the ith element of the vector; otherwise, the row contains zeros. If the value of the ith integer is 0, then the whole ith row should be 0.
To make this a whole lot simpler, here is a working reproducible example:
set.seed(1)
playv<-sample(0:5,20,replace=TRUE)#sample integer vector
playmat<-matrix(playv,nrow=length(playv),ncol=max(playv))#create matrix from vector
for (i in 1:length(playv)){
pos<-as.integer(playmat[i,1])
playmat[i,pos]<-1
playmat[i,-pos]<-0}
head(playmat)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 0 0 0 0
[2,] 0 1 0 0 0
[3,] 0 0 1 0 0
[4,] 0 0 0 0 1
[5,] 1 0 0 0 0
[6,] 0 0 0 0 1
The above solution is correct, I'm just looking to make something more robust.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…