The Question with example: In short I've been trying to learn how to work with matrices in R programming. I've been trying to gain access and modify elements directly surrounding a 1 with some probability of either a 0 or 1. An example would be in the bottom right hand corner of the matrix. Also I've been stumped on the edge cases.
//initial
1 0 0 1 0
1 0 0 0 0
0 0 0 0 0
0 0 0 1 0
0 0 0 0 0
//after
1 1 0 1 0
1 0 0 1 0
0 0 1 0 0
0 0 1 1 0
0 0 0 0 1
What have I tried?
I have tried the for loop approach which hasn't worked at all and also can't handle the edge of the matrix because the index would be out of bound.
for(row in 1:nrow(y)){
for(col in 1:ncol(y)){
if(y[row,col] == 2){
y[row+1,col] = sample(c(0,1), replace = TRUE, size = 1)
y[row+1,col+1] = sample(c(0,1), replace = TRUE, size = 1)
y[row+1,col-1] = sample(c(0,1), replace = TRUE, size = 1)
y[row-1,col] = sample(c(0,1), replace = TRUE, size = 1)
y[row-1,col-1] = sample(c(0,1), replace = TRUE, size = 1)
y[row-1,col+1] = sample(c(0,1), replace = TRUE, size = 1)
y[row,col+1] = sample(c(0,1), replace = TRUE, size = 1)
y[row,col-1] = sample(c(0,1), replace = TRUE, size = 1)
}
}