I have a matrix (1051*1051) that has 0zeros along its diagonal and values greater than 0zero everywhere else. The goal is to conditionally reassign some values in the matrix. For example, the criteria I would like to implement is this: If any element is greater than, say, 400, then that row/column element will be assigned a 0zero value.
This is how my code is setup as of now:
dl <- 400 # condition
for( i in 1:dim(DIST)[1] ) {
for( j in 1:dim(DIST)[1] ) {
if( DIST[i,j] > dl ) {
DIS[i,j] <- 0
}
}
}
DIST is the original matrix (1051*1051).
DIS is the copy of DIST and to be edited.
My question:
Is there any other way to do this? A faster way?
I have read that loops in R should be avoided. If anyone has a more efficient way please share.
Thank you.
Just use [] assignment:
See
?'['for how this works. The key is thatDIST>400produces a logical vector of lengthlength(DIST)(the number of elements in DIST), consisting of TRUE if the element is >400 and FALSE otherwise. That vector is then used to subset the matrix, and only the selected elements get assigned to.