wellokaythen
wellokaythen

Reputation: 11

How to fill matrix if row and column are a certain number in R?

I want to create a matrix such that if the (nth row - nth column) = 2 or 3, then it should be filled by some number say 5.

So matrix[7,9]=5; and matrix[5,2]=5; and matrix[13,15]=5 etc.

I tried

matrix <- matrix(nrow = n, ncol = n)
for (i in matrix[i,]){
  for (j in matrix[,j]){
    ifelse(((i-j) == 2|3), 5, 0)
  }
}

Obviously, this is wrong as i and j don't correspond to the first, second...nth row/column. Please help me out.

Upvotes: 1

Views: 234

Answers (1)

markus
markus

Reputation: 26343

Here is a way using row and col

n <- 10
mat <- matrix(nrow = n, ncol = n) 

row_col_diff <- row(mat) - col(mat)
mat[row_col_diff ==  2 | row_col_diff ==  3] <- 5
mat
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,]   NA   NA   NA   NA   NA   NA   NA   NA   NA    NA
# [2,]   NA   NA   NA   NA   NA   NA   NA   NA   NA    NA
# [3,]    5   NA   NA   NA   NA   NA   NA   NA   NA    NA
# [4,]    5    5   NA   NA   NA   NA   NA   NA   NA    NA
# [5,]   NA    5    5   NA   NA   NA   NA   NA   NA    NA
# [6,]   NA   NA    5    5   NA   NA   NA   NA   NA    NA
# [7,]   NA   NA   NA    5    5   NA   NA   NA   NA    NA
# [8,]   NA   NA   NA   NA    5    5   NA   NA   NA    NA
# [9,]   NA   NA   NA   NA   NA    5    5   NA   NA    NA
#[10,]   NA   NA   NA   NA   NA   NA    5    5   NA    NA

Upvotes: 1

Related Questions