OtagoHarbour
OtagoHarbour

Reputation: 4183

Vectorizing which statements in R

I currently have the following code.

names <- c("Red","Green","Blue","Orange","Yellow")
aMatrix <- matrix(data=0,nrow=5,ncol=5)
df <- data.frame(matrix(nrow=5,ncol=2))
colnames(df)=c("Number","name")    
selectedRows=sample(1:5, 5)
samples=sample(1:5, 5)
for (i in 1:5){
    df[i,"Number"]=i
    df[i,"name"]=names[samples[i]]
}
for (i in 1:5){
    aMatrix[i,which(names==df[selectedRows[i],"name"])]=1
}

Is there a way to vectorize the last loop so that it runs faster?

Upvotes: 2

Views: 44

Answers (1)

akrun
akrun

Reputation: 887691

It can be done by creating a column index with match, cbind the row index with the column index to extract the values from aMatrix and assign those to 1

aMatrix2 <- aMatrix # before the assignment in OP's code
aMatrix2[cbind(seq_len(nrow(aMatrix)), match(df$name[selectedRows], names))] <- 1

-checking

identical(aMatrix, aMatrix2)
#[1] TRUE

Upvotes: 2

Related Questions