From: <markleeds_at_verizon.net>
Date: Fri, 18 Jul 2008 17:17:36 -0500 (CDT)

This is for ACroske but I can't find his email so I'll just send it to the list. Hi ACroske: The code below takes a zeros and ones matrix and puts ones
in the places you wanted. It can be made shorter ( maybe ?. i haven't thought about that ) but first let me know if that's what you wanted ? The original matrix is called binary.matrix and the final matrix is called tempbinmat. it should work for any size matrix but i didn't check for speed so it might be slow if the original matrix is large.

# CREATE PROBABILITY MATRIX

prob.matrix<-matrix(runif(36,0,0.5),ncol=6)
#print(prob.matrix)

# CREATE BINARY MATRIX BASED ON PROB MATRIX
binary.matrix<-matrix(rbinom(length(prob.matrix),prob=prob.matrix,size=1),nrow=nrow(prob.matrix)) print(binary.matrix)

# CREATE DUMMY ROW AND COL AND
# ADD THEM TO THE MATRIX SO THAT
# LATER ON, WE DON"T HAVE TO WORRY
# ABOUT FILLING AN ELEMENT THAT
# ISN"T THERE

zerorow <- numeric(ncol(binary.matrix)+2) zerocol <- numeric(nrow(binary.matrix))

#ADD COL TO BEGINNING AND END

tempbinmat <- cbind(zerocol,binary.matrix,zerocol)
# ADD RO TO TOP AND BOTTOM

tempbinmat <- rbind(zerorow,tempbinmat,zerorow)
# GET RID OF NAMES

colnames(tempbinmat) <- NULL
rownames(tempbinmat) <- NULL

# FIND OUT WHERE ALL THE ONES ARE.
# ARR.IND = TRUE GIVES THEM BACK IN MATRIX FORM
whichres <- which(tempbinmat == 1, arr.ind=TRUE)

# THIS LAPPLY GOES THROUGH THE LOCATIONS WHERE
# THERE ARE ONES AND FINDS LOCATIONS WHERE
# ONES NEED TO BE ADDED

onespositions <- lapply(1:nrow(whichres),function(.rownum) {

rightspot <- c(whichres[.rownum,1], whichres[.rownum,2]+1)    leftspot <- c(whichres[.rownum,1], whichres[.rownum,2]-1)    belowspot <-c(whichres[.rownum,1]-1, whichres[.rownum,2])    abovespot <- c(whichres[.rownum,1]+1, whichres[.rownum,2])    temp <- rbind(rightspot,leftspot,belowspot,abovespot) })

# THIS SETS THE CONSTRUCTED INDICES TO 1
for ( i in 1:length(onespositions) ) {

tempbinmat[onespositions[[i]]] <- 1
}

#print(tempbinmat)

# NOW GET RID OF THE ROWS AND COLUMNS THAT WERE ARTIFICALLY
ADDED AT THE START TO MAKE THINGS EASIER tempbinmat <- tempbinmat[2:(nrow(tempbinmat)-1),2:(ncol(tempbinmat)-1)] print(tempbinmat)

R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Fri 18 Jul 2008 - 22:23:39 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 18 Jul 2008 - 23:31:48 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.