keila
keila

Reputation: 1

How to apply function to matrix elements based on row and column identity in R

I have a square matrix, and I'm trying to:

  1. Change only the off-diagonal elements
  2. Apply a function to each off-diagonal element based on the identity of the element's row and column, using a separate list of values of length row/column.

I want to multiply each element of the matrix by row number element of the list, and olumn number element of the list.

Here's the matrix and the list from which I want my function to draw values to multiply for each matrix element.

states <- matrix(seq(1,9,1), nrow=3,ncol=3)
print(states)
rates <- seq(1, 5,2)
print(rates)

So for example, I want to multiply 8 in the matrix by 3*5 since it is in the 2nd row and 3rd column.

I've indexed the off-diagonal elements (not sure if this was the best way for my purposes):

delta <- row(states)-col(states)

And tried to sapply:

sapply(states[delta>0],function(i) {
  i*rates[row(i)]*rates[col(i)]
print(states)
})

But I get the error message " Error in row(i) : a matrix-like object is required as argument to 'row' ". I know it's a problem with how I'm indexing the elements but can't think of a better way.

Thanks in advance!

Upvotes: 0

Views: 89

Answers (1)

keila
keila

Reputation: 1

Figured out the answer!

The problem arose from trying to pick out a single value in the matrix, which doesn't work for functions row() and col().

So rather than indexing as

rates[row(i)]

it needed to be

rates[row(states)[i]]

Upvotes: 0

Related Questions