我在R中有这个矩阵,从命令
中称为MRASTI genereatetMRASTI <- matrix(sample(data.matrix(pune, rownames.force=NA),
22000, replace=TRUE),
nrow=1000, byrow=TRUE)
我有这个间隔
x[(x>14274.19)&(x<14458.17)]
是具有9998个元素的向量。我想计算这个公式:
y <- 1 / length(MRASTI) * sum((MRASTI - x)^2)
其中x取自前一个区间的值。我怎么能在R? 谢谢
我尝试这个命令:
> for (i in 1:9998) {y<-1/length(MRASTI)*sum((MRASTI-x[i])^2)}
但这只生成一个值 谢谢
答案 0 :(得分:1)
问题在于此行中的y
:
for (i in 1:9998) {
y <- 1/length(MRASTI)*sum((MRASTI-x[i])^2)
}
在每次循环迭代中,您将覆盖y
。简单的解决方案是:
y <- numeric(length = 9998)
for (i in seq_along(y)) {
y[i] <- 1 / length(MRASTI) * sum((MRASTI - x[i])^2)
}
如果没有看到一些示例对象和代码来创建它们并运行代码,很难说我们是否可以为您进行矢量化,因此您不需要循环。