Apply an indexed function to each value in a matrix row

I want to apply a function exp(-r*(i/500))

to every value in a matrix row (where i

denotes a column number). I know how to do it with a loop, but I am trying to learn the "correct" method in R.

I thought about:

apply(st,1,function(v) { exp(-r * (i/500)*v })

      

but I don't know how to determine the value i

so that it increments for each column.

I know the loop will do this, but I'm pretty sure this is not the optimal method in R.

+3


source to share


3 answers


If you need to use apply

something like this?

> apply(as.matrix(seq_len(ncol(m))), 1, function(x) exp(-r * m[,x]/500))

      

Where m

is your matrix.



Of course, there is no need to use here apply

. You just need to build the appropriate matrix.

exp(-r * matrix(rep(1:ncol(m), nrow(m)), nrow=nrow(m), byrow=T)/500) * m

      

+3


source


Try this as it col(st)

will return a matrix the same size as st

filled with columns

st* exp(-r * (col(st)/500))

      



Unsurprisingly, there is a series function, and together they can be useful. Multiplication table:

m <- matrix(NA, 12,12)
m=col(m)*row(m)

      

+3


source


Maybe something like this?

## m is the matrix with your data
m <- matrix(1:50,ncol=10,nrow=5)
## m2 is a matrix with same dimensions and each element is the column number
m2 <- matrix(rep(1:ncol(m),nrow(m)),ncol=ncol(m),nrow=nrow(m),byrow=TRUE)
## Compute m2 such as each value is equal to expr(-r*(i/500))
m2 <- exp(-r*(m2/500))
## multiply m and m2
m*m2

      

+1


source







All Articles