r将索引函数应用于矩阵行中的每个值

  • 本文关键字:索引 函数 应用于
  • 更新时间 :
  • 英文 :


我想将函数exp(-r*(i/500))应用于矩阵行中的每个值(其中i表示列号)。我知道如何用循环来做这件事,但我正在努力学习R.中的"正确"方法

我想过:

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

但我不知道如何定义值i,这样它将为每列递增。

我知道循环可以实现这一点,但我相当确定这不是R.中的最佳方法

如果你必须使用apply,那么这样的东西?

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

其中m是您的矩阵。

当然,这里没有必要使用apply。你只需要构造一个合适的矩阵。

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

试试这个,因为col(st)将返回一个与st相同维度的矩阵,其中填充了列

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

毫不奇怪,还有一个行函数,它们结合在一起会很有用。乘法表:

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

也许是这样的?

## 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

最新更新